python - 对多列应用 lambda 函数

标签 python python-3.x pandas

假设我在 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.applySeries.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/

相关文章:

python - 在 Python pandas DataFrame 中交换值以清理数据的最佳方法是什么

python - pandas dtype 和 dtypes 有什么区别

python - 将字典中的值赋给对象

python - 这个链式分配是如何工作的?

python - 一定范围内的随机数组

python-3.x - python3打开文件并读取行

python - 使用 Matplotlib 创建箱线图

python - 如何避免将新行计为 Spark 中的单词?

python - “tee”不被识别为内部或外部命令、可操作程序或批处理文件

python - 计算所有列差异的最快方法