python - Pandas CSV 未检测到第二列

我有一个由某些程序生成的 CSV 文件。我正在尝试使用 panda 读取 CSV:

import pandas as pd
file = pd.read_csv('test.csv')

它正在成功读取它,我可以使用 file.columns 显示列

output: `Index(['col1', ' \tcol2', ' \tcol3',
       ' \tcol4', ' \tcol5', ' \tcol6', ' \tcol7',
       ' \tcol8', ' \tcol9', ' \tcol10', ' \tcol11',
       ' \tcol12', ' \tcol13'],
      dtype='object')`

我可以使用 column_1 = file.col1 读取第一列但是当我尝试读取任何其他列时,它给了我一个错误:AttributeError: 'DataFrame' object has no attribute 'col2'

我发现这可能是由于列中的制表符和空格,所以我尝试使用删除它们

file = file.replace(r'\r+|\n+|\t+','', regex=True) 但它没有删除任何东西。

根据许多其他答案,我也尝试了以下操作:

file = file.replace(to_replace=[r"\\t|\\n|\\r", "\t|\n|\r"], value=["",""], regex=True, inplace=True)

file = file.replace('\t','', regex=True)

但他们都没有删除任何东西。

回答1

我得到它使用:

file = file.rename(columns=lambda x: x.strip())

它删除了所有空格。我从这个答案中得到它:https://stackoverflow.com/questions/21606987/how-can-i-strip-the-whitespace-from-pandas-dataframe-headers

回答2

使用 df = df.rename(columns=lambda x: x.strip())

相似文章

r - 在 R 中加载 csv 数据框时添加列

我们正在Airbnb内部为我们的大学开展一个项目。我们加载了许多不同城市的列表,并希望将所有数据加载到一个相互绑定的数据框中。但是,我们解决了这个问题。现在我们需要为每个数据集添加一个列,说明它属于哪...

随机推荐

最新文章