Skip to main content
 首页 » 编程设计

python之Pandas :将 csv 文件加载为列表

2024年09月07日14zdz8207

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_id 作为字符串加载,如下所示 ['1','2','3']", ...

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

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

请您参考如下方法:

在加载数据时,指定一个 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]]