pandas将一列拆分为多个KeyError

时间:2016-10-25 13:37:52

标签: python pandas split

df = age;"job";"marital";"education";"default";"housing";"loan";"contact";"month";"day_of_week";"duration";"campaign";"pdays";"previous";"poutcome";"emp.var.rate";"cons.price.idx";"cons.conf.idx";"euribor3m";"nr.employed";"y"
0  30;"blue-collar";"married";"basic.9y";"no";"ye...                                                                                                                                                                          
1  39;"services";"single";"high.school";"no";"no"...                                                                                                                                                                          
2  25;"services";"married";"high.school";"no";"ye...                                                                                                                                                                          
3  38;"services";"married";"basic.9y";"no";"unkno...                                                                                                                                                                          
4  47;"admin.";"married";"university.degree";"no"...                                                                                                                                                                          
5  32;"services";"single";"university.degree";"no...                                                                                                                                                                          
6  32;"admin.";"single";"university.degree";"no";...                                                                                                                                                                          
7  41;"entrepreneur";"married";"university.degree...                                                                                                                                                                          
8  31;"services";"divorced";"professional.course"...                                                                                                                                                                          
9  35;"blue-collar";"married";"basic.9y";"unknown... 

有21个属性,我想将一列拆分为21列。

df['1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21'].apply(lambda x: pd.Series(x.split(';')))

然后它返回:

  

KeyError:'1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20'

有什么问题?

1 个答案:

答案 0 :(得分:3)

我认为您在read_csv中遗漏了sep=';'个参数,因为默认情况下sep=','

但如果需要按;拆分第一列,请使用str.splitiloc选择第一列:

print (df.iloc[:,0].str.split(';', expand=True))