首页 > 解决方案 > 当列包含某些文本时,将所有列值连接到 1 列

问题描述

我想创建一个名为“part_1_total”的新列,它将包含字符串 'Part 1' 的列的所有值粘贴在一起(对于下一组包含 'Part 2' 、 Part 3' 等的列也应该这样做...)

有没有快速的方法来做到这一点?

我的尝试:

# Attempt 1 yields 0 as it is to sum up numbers 
def calc_total(df,string='Part 1'):
    return df.loc[:,[x for x in df.columns if string in x]].sum(axis=1)

# Attempt number 2 pastes the column names into all the cells
asos['part_1_total'] = ''.join(asos.loc[:,[x for x in asos.columns if 'Part 1' in x]])


在此处输入图像描述

标签: pandastextconcatenationcontains

解决方案


我认为这只是列子集的 str 连接。

import pandas as pd
import numpy as np

df = pd.DataFrame(
    {'Part 1 - Body':[np.nan, '100% Other Material'],
     'Part 2 - Back':['43% Nickle', '20% Aluminum'],
     'Part 1 - Lining':['93% Cotton', '23% Spandex']}
    )

df['part_1_total'] = df[[c for c in df.columns if 'Part 1' in c]].apply(
        lambda x: x.str.cat(sep=', '), axis=1)

结果数据框:

         Part 1 - Body Part 2 - Back Part 1 - Lining                      part_1_total
0                  NaN    43% Nickle      93% Cotton                        93% Cotton
1  100% Other Material  20% Aluminum     23% Spandex  100% Other Material, 23% Spandex

您可以通过调整sep参数来调整您希望如何连接字符串(使用逗号、空格等)。有关在 pandas 中连接字符串列的更多信息,请参阅此答案。您可以使用''.joinin ,apply但这似乎不适用于 NaN。


推荐阅读