我有一个csv文件如下:
0 5
1 10
2 15
3 20
4 25
我想将其保存为x,y轴作为名称的数据框,然后绘制它。但是,当我分配x
,y
时,我得到一个混乱的DataFrame,发生了什么?
column_names = ['x','y']
x = pd.read_csv('csv-file.csv', header = None, names = column_names)
print(x)
x y
0 0 5 NaN
1 1 10 NaN
2 2 15 NaN
3 3 20 NaN
4 4 25 NaN
我试过没有为None
指定header
,但没有用。
答案 0 :(得分:20)
将参数sep="\s+"
或delim_whitespace=True
添加到read_csv
:
import pandas as pd
temp=u"""0 5
1 10
2 15
3 20
4 25"""
#after testing replace io.StringIO(temp) to filename
column_names = ['x','y']
df = pd.read_csv(pd.compat.StringIO(temp), sep="\s+", header = None, names = column_names)
print (df)
x y
0 0 5
1 1 10
2 2 15
3 3 20
4 4 25
或者:
column_names = ['x','y']
df = pd.read_csv(pd.compat.StringIO(temp),
delim_whitespace=True,
header = None,
names = column_names)
print (df)
x y
0 0 5
1 1 10
2 2 15
3 3 20
4 4 25
答案 1 :(得分:7)
你可以试试这个:
import pandas as pd
column_names = ['x','y']
df = pd.read_csv('csv-file.csv',header=None)
df.columns = column_names