将 pandas DF列表转换为字符串 [英] Converting a Panda DF List into a string

查看:547
本文介绍了将 pandas DF列表转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫数据框.列之一包含一个列表.我希望该列为单个字符串.

I have a panda data frame. One of the columns contains a list. I want that column to be a single string.

例如,我的列表['one','two','3']应该简单地为'1、2、3'

For example my list ['one','two','three'] should simply be 'one, two, three'

df['col'] = df['col'].astype(str).apply(lambda x: ', '.join(df['col'].astype(str)))

给我['一个,两个,三个],['四个','五个','六个'],其中第二个列表来自下一行.不用说,对于数百万行,这种跨行连接不仅是不正确的,而且还会杀死我的记忆.

gives me ['one, two, three],['four','five','six'] where the second list is from the next row. Needless to say with millions of rows this concatenation across rows is not only incorrect, it kills my memory.

推荐答案

在转换列表之前,您当然不应该转换为字符串.试试:

You should certainly not convert to string before you transform the list. Try:

df['col'].apply(', '.join)

还请注意,apply将函数应用于系列元素,因此在lambda函数中使用df['col']可能不是您想要的.

Also note that apply applies the function to the elements of the series, so using df['col'] in the lambda function is probably not what you want.

编辑:感谢 Yakym 指出不需要使用lambda函数

Edit: thanks Yakym for pointing out that there is no need for a lambda function.

这篇关于将 pandas DF列表转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆