我有一个具有1461属性的csv文件。我想把它加载到一个熊猫数据框中。问题是,许多行没有尾随连续列的值。因此,pandas由于长度不规则而导致解析错误。如何一次性放置前导列的缺失值并将csv文件加载到数据框中?
Edit1我们可以看到数据集csv文件如下
a,b,c,d,e,f,g,h,i""" 1,2,4,5 1,0,9,8,7,6,5,4,7 1,3,5,6,7 6,7,8,8,9,4,5,3,5"""我想要一个像下面这样的熊猫数据框
"""a b c d e f g h i
1 2 4 5 ? ? ? ? ?
1 0 9 8 7 6 5 4 7
1 3 5 6 7 ? ? ? ?
6 7 8 8 9 4 5 3 5"""用NaN代替?可以是好的
我们没有足够的逗号不等长的问题。
发布于 2017-03-09 14:17:15
似乎可以在read_csv中通过range对列名使用参数names (如果属性是列):
import pandas as pd
from pandas.compat import StringIO
temp=u"""
a,v
c,v,f,r
b,g
y"""
#after testing replace 'StringIO(temp)' to 'filename.csv'
#in real data change 4 to 1461
names = range(4)
df = pd.read_csv(StringIO(temp), names=names)
print (df)
0 1 2 3
0 a v NaN NaN
1 c v f r
2 b g NaN NaN
3 y NaN NaN NaN编辑:
temp=u"""a,b,c,d,e,f,g,h,i
1,2,4,5
1,0,9,8,7,6,5,4,7
1,3,5,6,7
6,7,8,8,9,4,5,3,5"""
#after testing replace 'StringIO(temp)' to 'filename.csv'
df = pd.read_csv(StringIO(temp))
print (df)
a b c d e f g h i
0 1 2 4 5 NaN NaN NaN NaN NaN
1 1 0 9 8 7.0 6.0 5.0 4.0 7.0
2 1 3 5 6 7.0 NaN NaN NaN NaN
3 6 7 8 8 9.0 4.0 5.0 3.0 5.0https://stackoverflow.com/questions/42688022
复制相似问题