簡體   English   中英

根據列標題合並Pandas中的列

[英]Combining columns in Pandas based on column header

我需要合並數據框中的列。

標頭將具有類似的名稱,但后綴不同,例如

A1 | A2 | A3 | B1 | B2 | B3

最后,我想將它們全部合並:

A | B

我有這行代碼,可以將一組已定義的列成功合並到一個列中:

df['A'] = df[['A1','A2','A3]].apply(' '.join, axis=1)

問題在於報頭不一致,可能存在“ 1”,“ 2”或“ 3”的任意組合-例如

A1 | A2 | A3 | B2 | C1 | C2 

從我看過的解決方案中,pandas不喜歡引用不存在的列,因此我不能將apply語句用作一攬子命令。

我無法在嵌套的“嘗試/除外”步驟列表之外查看解決方案。 如果有人有想法,我將不勝感激!

更新
感謝您的解決方案!!! 如果有人感興趣,這對我有用:

解決方案1

for h in headers:
    cols = [col for col in df.columns if col.split('[')[0] == h]
    if cols == []:
        cols = [col for col in df.columns if col == h and col.split('[')[0] not in headers] `

解決方案2

df.groupby(df.columns.str.split('[').str[0],axis=1).agg(lambda x :' '.join(x.values.tolist()))

您可以使用df.columns屬性找到相關的列

a_cols = [col for col in df.columns if col[0] == 'A']

然后將該列表用作您的apply函數的輸入

df['A'] = df[a_cols].apply(' '.join, axis=1)

例如,您有以下數據框

df=pd.DataFrame({'A1':['a'],'A2':['b'],'B2':['b'],'B3':['c']})

我們在列上使用groupby

df.groupby(df.columns.str[0],axis=1).agg(lambda x :','.join(x.values.tolist()))
Out[282]: 
     A    B
0  a,b  b,c
import string
df = pd.DataFrame(columns=['A1', 'A2','A3', 'B1','B2','C1'])

new_cols = {}
for new_col in list(string.ascii_uppercase):
    new_cols[new_col] = [col for col in df.columns if new_col in col]

for new_col in new_cols.keys():
    df[new_col] = df[new_cols[new_col]].apply(' '.join, axis=1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM