Pandas 当列包含特定文本时,将所有列值连接到一列中
我想创建一个名为“part_1_total”的新列,该列将包含字符串“part 1”的列的所有值粘贴在一起(下一组包含“part 2”、“part 3”等的列也应如此) 有没有快速的方法可以做到这一点 我的尝试:Pandas 当列包含特定文本时,将所有列值连接到一列中,pandas,text,concatenation,contains,Pandas,Text,Concatenation,Contains,我想创建一个名为“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]
# 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]])
我认为这只是列子集的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中连接字符串列的详细信息,请参见。您可以使用”。在应用中加入,但这似乎对NAN不起作用。可能重复:也可能重复:除了OP只想在列的子集上连接。非常感谢@jtorca-这正是我所需要的。再次感谢。