【问题标题】:Count the number of times a value from one dataframe has repeated in another dataframe计算一个数据帧中的值在另一个数据帧中重复的次数
【发布时间】:2018-06-07 12:00:51
【问题描述】:

我有 3 个数据框,分别是 A、B 和 C,在所有三个数据框中都有一个公共列“com_col”。我想在 B 中创建一个名为“com_col_occurrences”的新列,其计算方法如下。对于数据框 B 中 'com_col 中的每个值,检查该值是否在 A 中可用。如果可用,则返回该值在 A 中出现的次数。如果不是,则在 C 中检查它是否可用,如果可用,则返回它重复的次数。请告诉我如何在 Pandas 中为此编写函数。请在下面找到演示问题的示例代码。

import pandas as pd 

#Given dataframes
df1 = pd.DataFrame({'comm_col': ['A', 'B', 'B', 'A']})

df2 = pd.DataFrame({'comm_col': ['A', 'B', 'C', 'D', 'E']})

df3 = pd.DataFrame({'comm_col':['A', 'A', 'D', 'E']})  

# The value 'A' from df2 occurs in df1 twice. Hence the output is 2. 
#Similarly for 'B' the  output is 2. 'C' doesn't occur in any of the 
#dataframes. Hence the output is 0
# 'D' and 'E' occur don't occur in df1 but occur in df3 once. Hence 
#the output for  'D' and 'E' should be 1

#Output should be as shown below
df2['comm_col_occurrences'] = [2, 2, 0, 1, 1]

Output:

**df1**
         comm_col
0        A
1        B
2        B
3        A

**df3**
         comm_col
0        A
1        A
2        D
3        E

**df2**

         comm_col  
0        A         
1        B         
2        C         
3        D         
4        E  

**Output**
     comm_col  comm_col_occurrences
0        A                     2
1        B                     2
2        C                     0
3        D                     1
4        E                     1

提前致谢

【问题讨论】:

  • 你能发一个minimal reproducible example吗?
  • 是的,当然。给我一点时间
  • import pandas as pd #Given dataframes df1 = pd.DataFrame({'comm_col': ['A', 'B', 'B', 'A']}) df2 = pd.DataFrame ({'comm_col': ['A', 'B', 'C', 'D', 'E']}) df3 = pd.DataFrame({'comm_col':['A', 'A', ' D', 'E']}) # 来自 df2 的值 'A' 在 df1 中出现两次。因此输出为 2。#Similarly 对于“B”,输出为 2。“C”不会出现在任何 #dataframes 中。因此输出为 0 # 'D' 和 'E' 出现不会出现在 df1 中,但会出现在 df3 中一次。因此 # 'D' 和 'E' 的输出应该是 1 #Output 应该如下所示 df2['comm_col_occurrences'] = [2, 2, 0, 1, 1]
  • 你可以在问题中发布这个格式吗?
  • @HarvIpan 现在问题清楚了吗?请告诉我。

标签: pandas


【解决方案1】:

你需要:

result = pd.DataFrame({
    'df1':df1['comm_col'].value_counts(),
    'df2':df2['comm_col'].value_counts(),
    'df3':df3['comm_col'].value_counts()
})
result['comm_col_occurrences'] = np.nan
result.loc[result['df1'].notnull(), 'comm_col_occurrences'] = result['df1']
result.loc[result['df3'].notnull(), 'comm_col_occurrences'] = result['df3']
result['comm_col'] = result['comm_col'].fillna(0)
result = result.drop(['df1', 'df2', 'df3'], axis=1)

输出:

    comm_col  comm_col_occurrences
0        A                   2.0
1        B                   2.0
2        C                   0.0
3        D                   1.0
4        E                   1.0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多