python - Pandas-合并两列(一列是列表,一列是字符串)

标签 python pandas pandas-apply

想要合并两列,一列是字符串,另一列是字符串列表,想要将字符串追加到另一列的列表中,例如:

input: 
A   B    
5 [1,2]
2 [3,4]

return:
A  B     C
5 [1,2]  [1,2,5]
2 [3,4]  [3,4,2]

尝试使用 apply 但不知道如何处理不同类型的列

最佳答案

使用DataFrame.apply:

>>> df = pd.DataFrame({'A': ['5', '2'], 'B': [[1, 2], [3, 4]]})
>>> df['C'] = df.apply(lambda r: r['B'] + [r['A']], axis=1)
>>> df
   A       B          C
0  5  [1, 2]  [1, 2, 5]
1  2  [3, 4]  [3, 4, 2]

>>> df['C'] = df['B'] + df['A'].apply(lambda x: [x])
>>> df
   A       B          C
0  5  [1, 2]  [1, 2, 5]
1  2  [3, 4]  [3, 4, 2]

关于python - Pandas-合并两列(一列是列表,一列是字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46386183/

相关文章:

python - SqlAlchemy - PostgreSQL - 连接错误信息的 session

python - 通过将函数应用于另一个数据框的列来创建新数据框

python - Dataframe 上的 Pandas 条件返回 TypeError : '>' not supported between instances of 'str' and 'int'

python - 如何在 WMI 调用中分配变量?

python - wxPython UltimateListCtrl 以编程方式检查(勾选)列表项

python - geodjango 检查 PolygonField 中的 PointField

python - 根据匹配对不同工作表/文件中的值求和

python - UnicodeDecodeError 在对数据集进行词干处理时出现意外的数据结束

python - read_sql block 大小错误

python Pandas : can we avoid apply in this case of groupby/apply?