簡體   English   中英

Pandas:標志組,然后改變數據結構

[英]Pandas: Flag groups and then change the data structure

這是我的原始數據:

raw_data =  pd.DataFrame({'Year': [1991, 1991, 1991, 2000, 2000],
                          'ID': ['A', 'A', 'A', 'B', 'B',],
                          'Group': ['a', 'b', 'c', 'a', 'b'],
                          'score': [6252, 6252,6252, 2342, 2342]})

我需要生成三個組列,指示每個 ID 是否屬於該組。 Pivot function 只能改變數據結構,達到我的部分目的。

out_data = pd.DataFrame({'Year': [1991, 2000],
             'Group a':['Yes','Yes'],
             'Group b':['Yes','Yes'],
             'Group c':['Yes','No'],
             'ID': ['A', 'B'],
             'score': [6252, 2342]})

這是pivot_table的一個變體:

(df
 .pivot_table(index=['Year', 'ID'], columns='Group', values='score', aggfunc=any)
 .replace({True: 'Yes'}).fillna('No')
 .add_prefix('Group_')
 .reset_index().rename_axis(columns=None)
)

crosstab

(pd
 .crosstab([df['Year'], df['ID']], df['Group'], values=df['score'], aggfunc=any)
 .replace({True: 'Yes'}).fillna('No')
 .add_prefix('Group_')
 .reset_index().rename_axis(columns=None)
)

output:

   Year ID Group_a Group_b Group_c
0  1991  A     Yes     Yes     Yes
1  2000  B     Yes     Yes      No
def function1(dd:pd.DataFrame):
    return dd.assign(col1=1).pivot_table(index=['Year','ID','score'],columns='Group',values='col1')\
        .add_prefix('Group ')

raw_data.groupby(['Year','ID']).apply(function1)\
    .applymap(lambda x:"Yes" if pd.notna(x) else 'No')\
    .droplevel([0,1]).reset_index()

出去:

Group  Year ID  score Group a Group b Group c
0      1991  A   6252     Yes     Yes     Yes
1      2000  B   2342     Yes     Yes      No

暫無
暫無

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

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