2017-09-14 166 views
1

我想读取一个csv作为数据帧到Pandas中。Csv与熊猫数据框缺失列

我的CSV文件格式如下

a b c d 
0 1 2 3 4 5 
1 2 3 4 5 6 

当我读到有大熊猫,我得到以下数据框

a b c d 
0 1 2 3 4 5 
1 2 3 4 5 6 

的CSV当我执行print df.columns 我得到的是这样的:

Index([u'a', u'b', u'c', u'd'], dtype='object') 

而当我执行print df.iloc[0] 我得到:

a 2 
b 3 
c 4 
d 5 
Name: (0, 1) 

我想有一个东西像数据帧

a b c d col1 col2 
0 1 2 3 4 5 
1 2 3 4 5 6 

我不知道我有多少列必须有。但是我需要在标题之后的第一行中包含多少个值。我怎样才能做到这一点?

+0

这【答案】(https://stackoverflow.com/questions/34358196/read-csv-with-missing-incomplete-header-or-irregular-number-of-列)可以帮助 – floatingpurr

回答

2

这样做的一种方法是将数据读入两次。一旦与第一行(原列)跳过,只列名读取(和所有的行跳过)第二

df = pd.read_csv(header=None, skiprows=1) 
columns = pd.read_csv(nrows=0).columns.tolist() 
columns 

输出

['a', 'b', 'c', 'd'] 

现在找到丢失的列和使用的数量列表理解,使新列

num_missing_cols = len(df.columns) - len(columns) 
new_cols = ['col' + str(i+1) for i in range(num_missing_cols)] 
df.columns = columns + new_cols 
df 

    a b c d col1 col2 
0 0 1 2 3  4  5 
1 1 2 3 4  5  6 
+0

谢谢你,工作很好。我只是不得不将pd.read_clipboard()更改为pd.read_csv() –

+0

糟糕,我现在要修复它...谢谢 –