python - 根据不同数据框中的匹配值将摘要列添加到 Pandas 数据框中

标签 python python-3.x pandas dataframe

我有一个指示项目成员和项目开始日期的 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 , crosstabmerge :

##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/

相关文章:

python - Pandas groupby 总和如果组中的值

python - 为 Pandas 使用多个核心

python - 将每个字典值转换为 utf-8(字典理解?)

Python-Argparse : Default agrument that can be overridden

python - python中动态模块的init函数是什么?

python-3.x - np.where的不同类型的结果。x,y在两个条件下互换。我想念什么?

python - 在散列冲突中,CPython 如何知道哪个值存储在索引 HASHVALUE 以及哪个值存储在 RESOLUTIONINDEX

python - 在 Python 中写入空文件之前如何检查条件?

python - 当每个键有多个值时,根据值获取键列表

python - 将列级别由内而外