python - Pandas:如何添加一个组合其他列中的多个列表的新列?

标签 python pandas

我想将包含列表的多个列的内容合并到只有一个列表的新列中。

  Name            list0         list1                     list2
0    a  [Now, Now, Now]          None  [works!, works!, works!]
1    b  [Now, Now, Now]  [it, it, it]                      None
2    c  [Now, Now, Now]  [it, it, it]  [works!, works!, works!]

新列应如下所示:

0              [Now, Now, Now, works!, works!, works!]
1                          [Now, Now, Now, it, it, it]
2    [Now, Now, Now, it, it, it, works!, works!, wo...

我的解决方案:

#Column of empty lists
new['helper']=np.empty((len(new), 0)).tolist()

#Missing values to empty lists
new['list0']=new['list0'].fillna(new['helper'])
new['list1']=new['list1'].fillna(new['helper'])
new['list2']=new['list2'].fillna(new['helper'])

#Add Lists
new['together']=new['list0']+new['list1']+new['list2']

但是必须有一个更快或至少更好的解决方案! 有什么提示吗?

最佳答案

我相信你需要:

cols = ['list0','list1','list2']
df[cols] = df[cols].applymap(lambda x: [] if x == None else x)

关于python - Pandas:如何添加一个组合其他列中的多个列表的新列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47571209/

相关文章:

python - 针对本地文件的 Scrapy shell

python - 使用 pandas 根据特定列中的条件替换日期值

python - 动态创建连续数字的嵌套列表

python - 如何使用 pandas Groupby 将不同的聚合函数应用于同一列

python - 如何在 Python 中循环调用函数

在 virtualenv 中找不到从 Tensorflow 构建的 Python.h

python - 在 Miniconda 上安装 Jupyter Notebook

python - requests.codes.ok 是否包含 304?

python - 为什么 pandas groupby().transform() 需要唯一索引?

python - 使用变量的 Pandas Sqlite 查询