简体   繁体   English

熊猫-合并两列(一列是列表,一列是字符串)

[英]Pandas- merge two columns (one is list, one is string)

Want to merge two columns, one column is string, the other column is lists of strings, want to append the string to the list of the other, for example: 要合并两列,一列是字符串,另一列是字符串列表,要将字符串追加到另一列的列表,例如:

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]

Tried to use apply but not how to deal with columns with different types 试图使用apply但不如何处理不同类型的列

Using DataFrame.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]
df['C']=[[x[0]] + x[1] for x in df.values.tolist()]
df
Out[435]: 
   A       B          C
0  5  [1, 2]  [5, 1, 2]
1  2  [3, 4]  [2, 3, 4]

If using apply 如果使用apply

df = pd.DataFrame({'A': ['523', '212'], 'B': [[1, 2], [3, 4]]})

df.A.apply(lambda x : [x])+df.B
Out[465]: 
0    [523, 1, 2]
1    [212, 3, 4]
dtype: object
df.assign(C=[[x, y, z] for x, (y, z) in zip(df.A, df.B)])

   A       B          C
0  5  [1, 2]  [5, 1, 2]
1  2  [3, 4]  [2, 3, 4]

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

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