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

问题描述 投票:1回答:1
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']", ...

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

[list([1,2,3]), list([6,2,1]), list([4,3,9])]
python pandas csv numpy
1个回答
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]]
© www.soinside.com 2019 - 2024. All rights reserved.