[英]Apply lambda function on multiple columns
让我们假设我在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(' '))
样本数据
A B
0 [asdf, asf] [eeee, tttt]
df['combined'] = df.apply(lambda x: [' '.join(i) for i in list(x[['A','B']])], axis=1)
产量
A B combined
0 [asdf, asf] [eeee, tttt] [asdf asf, eeee tttt]
更新
df[['A','B']] = df.apply(lambda x: pd.Series([' '.join(x['A']),' '.join(x['B'])]), axis=1)
产量
A B
0 asdf asf eeee tttt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.