我的 CSV 文件在标题行中包含 #
:
s = '#one two three\n1 2 3'
如果我使用 pd.read_csv
#
符号进入第一个标题:
import pandas as pd
from io import StringIO
pd.read_csv(StringIO(s), delim_whitespace=True)
#one two three
0 1 2 3
如果我设置参数 comment='#'
,则 pandas
会完全忽略该行。
有没有简单的方法来处理这种情况?
第二个相关的问题是在这种情况下我如何处理引用,它在没有 #
的情况下工作:
s = '"one one" two three\n1 2 3'
print(pd.read_csv(StringIO(s), delim_whitespace=True))
one one two three
0 1 2 3
它不适用于#
:
s = '#"one one" two three\n1 2 3'
print(pd.read_csv(StringIO(s), delim_whitespace=True))
#"one one" two three
0 1 2 3 NaN
谢谢!
++++++++++更新
这里是第二个例子的测试。
s = '#"one one" two three\n1 2 3'
# here I am cheating slicing the string
wanted_result = pd.read_csv(StringIO(s[1:]), delim_whitespace=True)
# is there a way to achieve the same result configuring somehow read_csv?
assert wanted_result.equals(pd.read_csv(StringIO(s), delim_whitespace=True))
最佳答案
您可以这样重命名 read_csv()
输出的第一个 header :
import pandas as pd
from io import StringIO
df = pd.read_csv(StringIO(s), delim_whitespace=True)
new_name = df.columns[0].split("#")[0]
df.rename(columns={df.columns[0]:new_name})
关于python - 使用带有注释标题的 pandas 读取 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30311776/