python - 在多列上应用 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')
如何将此功能应用于多列(一行)?
我这么说是因为我可以在每一列分别应用该函数或定义一个函数并调用它以使其工作。
但是,我正在寻找最简洁的解决方案。
解决方案
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(' '))
推荐阅读
- arduino - 使用 PlatformIO (Arduino) 从内部振荡器运行 STM32F103?
- typescript - 为什么 querySelectorAll('div') 返回 HTMLDivElement 列表但 querySelectorAll('div.className') 返回 TypeScript 中的 Element 列表
- python - 我正在查看列表二中的项目是否是列表一中每个位置数据的三倍
- database - 3NF 表是否可以有一个具有重复值的 PK,但所有非键都依赖于 PK(无传递依赖)?
- spring-kafka - 重新排队kafka主题中的失败记录
- python - 获取url图片scrapy
- javascript - 引导卡垂直显示而不是响应式
- android - 在 Xamarin 中迁移到 Android X 后出现 MediaSessionCompat_OnActiveChangeListenerImplementor 错误
- angular - Angular NgModule 文档混乱
- python - 我怎么说:“如果 VALUE 减少:”在 Python 中?