简体   繁体   English

Pandas 将每个单元格都是字符串列表的列转换为整数列表

[英]Pandas convert column where every cell is list of strings to list of integers

I have a dataframe with columns that has list of numbers as strings:我有一个数据框,其中的列具有数字列表作为字符串:

C1 C2 l
1   3 ['5','9','1']
7   1 ['7','1','6']

What is the best way to convert it to list of ints?将其转换为整数列表的最佳方法是什么?

C1 C2 l
1   3 [5,9,1]
7   1 [7,1,6]

Thanks谢谢

Pandas' dataframes are not designed to work with nested structures such as lists. Pandas 的数据框不适用于列表等嵌套结构。 Thus, there is no vectorial method for this task.因此,这个任务没有矢量方法。

You need to loop.你需要循环。 The most efficient is to use a list comprehension ( apply would also work but with much less efficiency).最有效的是使用列表理解( apply也可以,但效率要低得多)。

df['l'] = [[int(x) for x in l] for l in df['l']]

NB.注意。 There is no check.没有检查。 If you have anything that cannot be converted to integers, this will trigger an error!如果您有任何无法转换为整数的内容,则会触发错误!

Output:输出:

  C1 C2         l
0  1  3 [5, 9, 1]
1  7  1 [7, 1, 6]

You can try你可以试试

df['l'] = df['l'].apply(lambda lst: list(map(int, lst)))
print(df)

   C1  C2          l
0   1   7  [5, 9, 1]
1   3   1  [7, 1, 6]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM