Pandas:将csv文件作为列表加载

时间:2017-12-24 09:51:02

标签: python pandas csv numpy

customer  gender customer_ids
  1         0       [1,2,3]
  2         1       [6,2,1]
  3         0       [4,3,9]

我在csv文件中有一些数据如上所述。我像这样加载csv文件

df = pd.read_csv('customer.csv', sep='\t')

这会将customer_ids加载为字符串,如"['1','2','3']", ...

但我需要将customer_ids数据作为像这样的numpy数组

[list([1,2,3]), list([6,2,1]), list([4,3,9])]

1 个答案:

答案 0 :(得分:1)

加载数据时,请指定converters参数 -

df = pd.read_csv('customer.csv', sep='\t', converters={'customer_ids' : pd.eval})
df

   customer  gender customer_ids
0         1       0    [1, 2, 3]
1         2       1    [6, 2, 1]
2         3       0    [4, 3, 9]

df.customer_ids.tolist()
[[1, 2, 3], [6, 2, 1], [4, 3, 9]]