You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将TXT文本文件内容转换为Pandas DataFrame格式

实现方法

你的txt文件结构是前10行作为列名,后续每连续10行对应一条NFT数据,按以下步骤处理即可:

注:该txt不是常规的按行存储单条记录、列间用分隔符拆分的格式,而是单行列值的存储结构,所以不能直接用pandas内置的read_csv/read_table方法读取,需要先手动做行分组处理。

  • 第一步:读取txt文件的全部行,过滤掉每行首尾的空白字符和空行
  • 第二步:提取前10行作为DataFrame的列名
  • 第三步:将剩余的行按每10个元素为一组拆分,每组对应一条完整的NFT数据
  • 第四步:将拆分后的数据传入pandas生成DataFrame,可根据需要清理数值格式方便后续计算

示例代码如下:

import pandas as pd

# 替换为你的txt文件实际路径
file_path = "nft_data.txt"

# 读取所有行,去除换行符、空行
with open(file_path, "r", encoding="utf-8") as f:
    all_lines = [line.strip() for line in f if line.strip()]

# 提取列名
col_names = all_lines[:10]
# 剩余行按每10个为一组拆分
data_list = [all_lines[i:i+10] for i in range(10, len(all_lines), 10)]
# 生成DataFrame
nft_df = pd.DataFrame(data_list, columns=col_names)

# 可选操作:把带逗号、百分号的文本格式数值转为可计算的数值类型
nft_df["Volume (ETH)"] = nft_df["Volume (ETH)"].str.replace(",", "").astype(float)
nft_df["Market Cap (ETH)"] = nft_df["Market Cap (ETH)"].str.replace(",", "").astype(float)
nft_df["#Transactions"] = nft_df["#Transactions"].str.replace(",", "").astype(int)
nft_df["#Wallets"] = nft_df["#Wallets"].str.replace(",", "").astype(int)
nft_df["% Opensea+Rarible"] = nft_df["% Opensea+Rarible"].str.replace("%", "").astype(float) / 100

按你提供的示例内容运行后,会得到包含2条NFT数据、10个列的DataFrame,完全符合你的需求。

内容的提问来源于stack exchange,提问作者hengjuice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 18:36:03