read_csv无法在此文件上正确读取列名? [英] read_csv doesn't read the column names correctly on this file?
本文介绍了read_csv无法在此文件上正确读取列名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个csv文件,如下所示:
I have a csv file as follows:
0 5
1 10
2 15
3 20
4 25
我想将其另存为以x,y轴为名称的数据框,然后将其绘制.但是,当我分配x
,y
时,我搞砸了DataFrame,这是怎么回事?
I want to save it as a dataframe with x,y axes as names, then plot it. However when I assign x
,y
I get a messed up DataFrame, what is happening?
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
我尝试不为header
指定None
,但无济于事.
I've tried without specifying None
for header
, to no avail.
推荐答案
将参数sep="\s+"
或delim_whitespace=True
添加到
Add parameter sep="\s+"
or delim_whitespace=True
to 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
这篇关于read_csv无法在此文件上正确读取列名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文