gpt4 book ai didi

python - Pandas read_table 使用第一列作为索引

转载 作者:太空狗 更新时间:2023-10-29 20:45:34 27 4
gpt4 key购买 nike

我这里有个小问题。我有一个 txt 文件,其中包含以下形式的行(比方说第 1 行):

id1-a1-b1-c1

我想使用 pandas 将其加载到数据框中,索引为 id,列名称为“A”、“B”、“C”,值分别为 ai、bi、ci

最后我希望数据框看起来像:

    'A'   'B'  'C'
id1 a1 b1 c1
id2 a2 b2 c2
... ... ... ...

我可能想按 block 读取文件很大,但假设我一次读取:

with open('file.txt') as f:
table = pd.read_table(f, sep='-', index_col=0, header=None, lineterminator='\n')

并重命名列

table.columns = ['A','B','C']

我当前的输出是这样的:

    'A'   'B'  'C'
0
id1 a1 b1 c1
id2 a2 b2 c2
... ... ... ...

有一行我无法解释

谢谢

编辑

当我尝试添加字段时

chunksize=20

做完之后:

for chunk in table:
print(chunk)

我收到以下错误:

pandas.parser.CParserError: Error tokenizing data. C error: Calling read(nbytes) on source failed. Try engine='python'.

最佳答案

如果您在读取文件之前知道列名称,请使用 read_tablenames 参数传递列表:

with open('file.txt') as f:
table = pd.read_table(f, sep='-', index_col=0, header=None, names=['A','B','C'],
lineterminator='\n')

哪些输出:

      A   B   C
id1 a1 b1 c1
id2 a2 b2 c2

关于python - Pandas read_table 使用第一列作为索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28200404/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com