假设我在 pandas
中有这个 DataFrame
:
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')
如何将此函数应用于多列(一行)?
我在一行中这么说是因为我可以在每一列单独应用该函数,或者定义一个函数并调用它以使其工作。
但是,我正在寻找最简洁的解决方案。
最佳答案
使用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(' '))
关于python - 对多列应用 lambda 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56631754/