我有一个指示项目成员和项目开始日期的 DataFrame,以及指示出生日期的第二个 DataFrame。我正在尝试根据每个项目的开始添加一些列,以指示某些年龄段的总人数。
print(projects)
Start John Bob Gladys
Project
A 2014-01-08 1 0 0
B 2016-08-09 0 1 1
C 2018-02-06 0 1 0
print(birthdays)
birth
name
John 1983-04-06
Gladys 1969-08-02
Bob 1946-11-03
我考虑过使用 .apply()
或 .iterrows()
方法,但我什至不知道从哪里开始。真正的 DataFrame 有更多的列和行,所以我需要避免按名称调用任何列。
这就是我想要完成的:
Start John Bob Gladys 25-34 35-45 46-55 56+
Project
A 2014-01-08 1 0 0 1 0 0 0
B 2016-08-09 0 1 1 0 0 1 1
C 2018-02-06 0 1 0 0 0 0 1
关于从哪里开始有什么建议吗?
最佳答案
这是使用 melt
的一种方法, cut
, crosstab
和 merge
:
##unpivot the dataframe keeping Start as index and keep only value ==1
melt_=projects.melt('Start').query('value==1')
#map the variable column from above with our birthday` dataframe squeezed into a series.
#Once mapped, subtract with the `Start` column to find out year difference.
Age=(melt_.Start-melt_.variable.map(birthdays.squeeze())).dt.days//365
#using pd.cut , we cut the Age into bins and assign our labels.
bins=[25,35,45,55,np.inf]
labels=['25-34','35-45','46-55','56+']
melt_=melt_.assign(Age=pd.cut(Age,bins,labels=labels))
最后用 pd.crosstab(melt_.Start,melt_.Age)
的 crosstab
输出与原始 df 合并:
projects.merge(pd.crosstab(melt_.Start,melt_.Age).reindex(columns=labels,fill_value=0)
,left_on='Start',right_index=True)
Start John Bob Gladys 25-34 35-45 46-55 56+
Project
A 2014-01-08 1 0 0 1 0 0 0
B 2016-08-09 0 1 1 0 0 1 1
C 2018-02-06 0 1 0 0 0 0 1
注意:预期的输出是错误的,因为 Bob
年长并且根据项目日期是 56+
。
关于python - 根据不同数据框中的匹配值将摘要列添加到 Pandas 数据框中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57684453/