gpt4 book ai didi

python - 使用 Pandas 读取可变列标题时出现问题

转载 作者:行者123 更新时间:2023-12-01 01:38:11 24 4
gpt4 key购买 nike

我有一个 python 脚本,可以从 csv 文件中提取数据进行处理。我正在使用的数据看起来像这样

Time.     Col1.     Col2.     Col3.     Important
0.1 .02 .03 .02 .02
0.2. .03 .03 .02 .03

该脚本提取“时间”和“重要”列进行处理。当所有列都存在时,脚本可以正常使用

# specify the row headers seven lines down the file
names = ['Time (s)', 'Col1', 'Col2', 'Col3', 'Important']
df = pd.read_csv(fle,
delim_whitespace=True,
error_bad_lines=False,
encoding='utf-8',
names=names,
skiprows=7)

我的问题是,在生成文件时,用户可以拒绝某些列,这意味着我可能会少用一列。

Time.     Col1.    Col3.     Important
0.1 .02 .03 .02
0.2. .03 .03 .03

但是由于我的“名称”列表包含文件中可能存在的所有标题,因此脚本无法识别列标题,也不会处理这些文件。 (它不会产生错误,只是生成的图是空白的,就好像没有数据一样)。

此脚本循环访问包含 50 个左右文件的文件夹,这些文件有 3 到 9 列,但其中两列始终是“时间”和“重要”。

有没有办法告诉pandas“名称”列表中的部分或全部列标题可能存在?

我尝试将“名称”缩短为仅“时间”和“重要”,但是当我必须对时间列的特定位置建立索引时,这会在代码中生成错误。

Traceback (most recent call last):
File "...inter-through-filesv2.py", line 55, in <module>
loop_start = df[df['Time (s)'] == start].index.item()
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pandas/core/base.py", line 719, in item
return self.values.item()
ValueError: can only convert an array of size 1 to a Python scalar

最佳答案

Is there a way to tell pandas that not all of the column headings in the 'names' list may be present?

您可以简单地省略 names 参数:

df = pd.read_csv(fle, delim_whitespace=True, error_bad_lines=False,
encoding='utf-8', skiprows=7)

然后在后续步骤中分配列名称:

n = len(df.columns)
df.columns = ['Time (s)'] + [f'Col{i}' for i in range(1, n-1)] + ['Important']

关于python - 使用 Pandas 读取可变列标题时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52186560/

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