pandas 如何使用Python将数据从一列传输到多列?

pjngdqdw  于 2022-11-20  发布在  Python
关注(0)|答案(2)|浏览(150)

如何使用python从“工作日”列和多个列(星期一、星期二、星期三......)传输数据,反之亦然

buyer    weekday    
0      A        Saturday
1      A        Friday
2      B        Monday
3      B        Tuesday
4      B        Thursday
5      C        Monday

预期结果:

buyer   Monday Tuesday Wednesday Thursday Friday Saturday Sunday
0      A                                           Y       Y       
1      B         Y       Y                 Y                            
2      C         Y
kcwpcxri

kcwpcxri2#

选项#1

为值引入一个虚拟列并使用pivot()

import calendar
weekdays = list(calendar.day_name)

df = pd.DataFrame({'buyer': ['A', 'A', 'B', 'B', 'B', 'C'],
                   'weekday': ['Saturday', 'Friday', 'Monday', 'Tuesday', 'Thursday', 'Monday']})

df["dummy"] = "Y"

df = df.pivot(index="buyer", columns="weekday", values="dummy").reindex(labels=weekdays, axis=1).fillna("").reset_index().rename_axis(columns={"weekday": ""})

[Out]:
  buyer Monday Tuesday Wednesday Thursday Friday Saturday Sunday
0     A                                        Y        Y       
1     B      Y       Y                  Y                       
2     C      Y

选项2

使用groupbysizeunstack的组合,最后使用replace值:

import calendar
weekdays = list(calendar.day_name)

df = pd.DataFrame({'buyer': ['A', 'A', 'B', 'B', 'B', 'C'],
                   'weekday': ['Saturday', 'Friday', 'Monday', 'Tuesday', 'Thursday', 'Monday']})

df = df = df.groupby(["buyer", "weekday"]).size().unstack(fill_value=0).replace({1:"Y",0:""}).reindex(labels=weekdays, axis=1).fillna("").reset_index().rename_axis(columns={"weekday": ""})

[Out]:
  buyer Monday Tuesday Wednesday Thursday Friday Saturday Sunday
0     A                                        Y        Y       
1     B      Y       Y                  Y                       
2     C      Y

相关问题