我有一个由某些程序生成的 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())