为什么这个Pandas csv导入失败?

时间:2016-03-10 18:34:21

标签: python csv pandas

我正在尝试导入以下csv文本:

name, favorites, age, other_hobbies
joe, "[madonna, elvis, u2]", 28, "[football, cooking]"
mary, "[lady gaga, adele]", 36, "[]"

使用以下pandas命令

file_name = "new_data.csv"
df = pd.read_csv(file_name, sep =",")
print(df)

我得到了这个结果:

                             name  favorites          age  other_hobbies
joe   "[madonna    elvis     u2]"         28   "[football      cooking]"
mary  "[lady gaga  adele]"     36       "[]"          NaN            NaN

为什么会发生这种情况,如何让pandas正确阅读?

1 个答案:

答案 0 :(得分:2)

skipinitialspace与sep:

一起传递
df = pd.read_csv("in.csv",sep="," , skipinitialspace=1)

print(df)

输出:

   name             favorites  age        other_hobbies
0   joe  [madonna, elvis, u2]   28  [football, cooking]
1  mary    [lady gaga, adele]   36                   []