python - 列表的列,将列表转换为字符串作为新列

标签 python string pandas list

我有一个包含一列列表的数据框,可以使用以下方式创建:

import pandas as pd
lists={1:[[1,2,12,6,'ABC']],2:[[1000,4,'z','a']]}
#create test dataframe
df=pd.DataFrame.from_dict(lists,orient='index')
df=df.rename(columns={0:'lists'})

数据框 df 看起来像:

                lists
1  [1, 2, 12, 6, ABC]
2     [1000, 4, z, a]

我需要创建一个名为“liststring”的新列,它获取 lists 中每个列表的每个元素,并创建一个字符串,每个元素用逗号分隔。每个列表的元素可以是intfloatstring。所以结果是:

                lists    liststring
1  [1, 2, 12, 6, ABC]  1,2,12,6,ABC
2     [1000, 4, z, a]    1000,4,z,a

我尝试过各种方法,包括来自 Converting a Panda DF List into a string 的:

df['liststring']=df.lists.apply(lambda x: ', '.join(str(x)))

但不幸的是,结果需要每个字符并用逗号分隔:

                lists                                         liststring
1  [1, 2, 12, 6, ABC]  [, 1, ,,  , 2, ,,  , 1, 2, ,,  , 6, ,,  , ', A...
2     [1000, 4, z, a]  [, 1, 0, 0, 0, ,,  , 4, ,,  , ', z, ', ,,  , '...

在此先感谢您的帮助!

最佳答案

列表理解

如果性能很重要,我强烈推荐这个解决方案和 I can explain why.

df['liststring'] = [','.join(map(str, l)) for l in df['lists']]
df

                lists    liststring
0  [1, 2, 12, 6, ABC]  1,2,12,6,ABC
1     [1000, 4, z, a]    1000,4,z,a

您可以使用函数将其扩展到更复杂的用例。

def try_join(l):
    try:
        return ','.join(map(str, l))
    except TypeError:
        return np.nan

df['liststring'] = [try_join(l) for l in df['lists']]

Series.apply/Series.agg with ','.join

您需要先将列表项转换为字符串,这就是 map 派上用场的地方。

df['liststring'] = df['lists'].apply(lambda x: ','.join(map(str, x)))

或者,

df['liststring'] = df['lists'].agg(lambda x: ','.join(map(str, x)))

<!->

df
                lists    liststring
0  [1, 2, 12, 6, ABC]  1,2,12,6,ABC
1     [1000, 4, z, a]    1000,4,z,a

pd.DataFrame 构造函数与 DataFrame.agg

非循环/非 lambda 解决方案。

df['liststring'] = (pd.DataFrame(df.lists.tolist())
                      .fillna('')
                      .astype(str)
                      .agg(','.join, 1)
                      .str.strip(','))

df
                lists    liststring
0  [1, 2, 12, 6, ABC]  1,2,12,6,ABC
1     [1000, 4, z, a]    1000,4,z,a

关于python - 列表的列,将列表转换为字符串作为新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45306988/

相关文章:

python - pandas .diff 按行的多索引值

python - 将 CSV 转置为 JSON

c++ - 使用区域设置在字符串中查找子字符串

python pandas dataframe 将字符串值的末尾替换为另一个字符

python - 使用 pandas 对 Excel 列进行排序

python - 在pandas的分组数据中插入值为0的缺失记录

python - 监控数据库相关事件的最佳实践

Python导入范围问题

Python 的引用传递

java - Web View 中的字符串模式