首页 > 解决方案 > 在多列上应用 lambda 函数

问题描述

假设我有DataFrame这个pandas

    year    text_1                 text_2
0   1999    ['Sunny', 'weather']   ['Foggy', 'weather']
1   2005    ['Rainy, 'weather']    ['Cloudy', 'weather']

我想把它改成这样:

    year    text_1           text_2
0   1999    'Sunny weather'  'Foggy weather'
1   2005    'Rainy weather'  'Cloudy weather'

出于这个原因,我这样做:

df[['text_1', 'text_2']] = df[['text_1', 'text_2']].apply(lambda x: ' '.join(x), axis=1)

但后来我收到以下错误:

TypeError: ('sequence item 0: expected str instance, list found', 'occurred at index 0')

另外,我这样做:

df = df.apply(lambda x: ' '.join(x['text_1'], x['text_2'],), axis=1)

但后来我收到以下错误:

TypeError: ('join() takes exactly one argument (2 given)', 'occurred at index 0')

如何将此功能应用于多列(一行)?

我这么说是因为我可以在每一列分别应用该函数或定义一个函数并调用它以使其工作。

但是,我正在寻找最简洁的解决方案。

标签: pythonpython-3.xpandas

解决方案


DataFrame.applymap如果需要明智地处理每个值元素,请使用:

df[['text_1', 'text_2']] = df[['text_1', 'text_2']].applymap(' '.join)
print (df)
   year         text_1          text_2
0  1999  Sunny weather   Foggy weather
1  2005  Rainy weather  Cloudy weather

DataFrame.apply结合Series.str.join

df[['text_1', 'text_2']] = df[['text_1', 'text_2']].apply(lambda x: x.str.join(' '))

推荐阅读