如何计算一个数据框中分类出现的次数并映射到另一个数据框中?

时间:2019-12-16 16:52:53

标签: python pandas dataframe

感谢您提供的任何帮助。

我有两个数据框:

df1
+-----+----------+
| key | category |
+-----+----------+
|   1 | B        |
|   1 | A        |
|   1 | A        |
|   2 | C        |
|   2 | B        |
|   3 | C        |
|   3 | B        |
|   3 | C        |
|   4 | B        |
|   4 | B        |
+-----+----------+

df2
+-----+----------+
| key | is_thing |
+-----+----------+
|   1 | yes      |
|   2 | yes      |
|   3 | yes      |
|   4 | no       |
+-----+----------+

我需要计算每个键在每个df1中出现每个类别的次数,并将每个键的总和最高的类别映射到df2,这样没有多数的类别会导致{{ 1}},所需的输出是:

NaN

如何使用Python和熊猫做到这一点?下面的可复制程序:

+-----+----------+----------+
| key | is_thing | category |
+-----+----------+----------+
|   1 | yes      | A        |
|   2 | yes      | NaN|
|   3 | yes      | C        |
|   4 | no       | B        |
+-----+----------+----------+

非常感谢您提供的任何帮助。谢谢。

3 个答案:

答案 0 :(得分:4)

这是使用crosstab()np.where()idxmax的一种方法:

m=pd.crosstab(df1['key'],df1['category'])
cond=m.isin(m.max(1)).sum(1)

d=dict(zip(m.index,np.where(cond.eq(1),m.idxmax(1),np.nan)))
df2['category']=df2['key'].map(d)
#df_desired=df2.assign(category=df2['key'].map(d)) for a new df keeping df2 same
print(df2)

   key is_thing category
0    1      yes        A
1    2      yes      NaN
2    3      yes        C
3    4       no        B

答案 1 :(得分:3)

new_df = pd.merge(df1, df2, how = 'left', left_on='key', right_on='key')

new_df.groupby(['key', 'is_thing'])['category'].agg(lambda s: s.mode()).map(lambda x: x if np.isscalar(x) else None)

>>> output  #  the index is (key, is_thing) (so reset it if you want).

1   yes A
2   yes 
3   yes C
4   no  B

答案 2 :(得分:2)

使用:

df2['category']=df2['key'].map(

  df1.groupby('key')
     .category
     .value_counts()
     .groupby(level=0)
     .filter(lambda x: x.nunique() == len(x)) 
     .unstack()
     .idxmax(1)
)
print(df2)

   key is_thing category
0    1      yes        A
1    2      yes      NaN
2    3      yes        C
3    4       no        B