首页 > 解决方案 > Python pandas:根据条件从多个数据框中访问数据

问题描述

我必须计算一个指标,该指标需要我从多个列中找到同一个“用户”的属性。例如,我有两个数据框,如下所示:

calls_per_month.head(10)
    user_id month   call_date
0   1000    12  16
1   1001    8   27
2   1001    9   49
3   1001    10  65
4   1001    11  64
5   1001    12  56
6   1002    10  11
7   1002    11  55
8   1002    12  47
9   1003    12  149

internet_per_month.head(10)

 user_id session_date mb_used
0   1000    12  2000.0
1   1001    8   7000.0
2   1001    9   14000.0
3   1001    10  23000.0
4   1001    11  19000.0
5   1001    12  20000.0
6   1002    10  7000.0
7   1002    11  20000.0
8   1002    12  15000.0
9   1003    12  28000.0

我想计算一个指标,对于他们使用互联网或拨打电话的每个月的每个 user_id 来说,它看起来像这样:`usage = mb_used + call_date' 这将是一个看起来像的列(我已经做了手工计算):

 user_id month usage
0   1000    12  2016
1   1001    8   7027
2   1001    9   14049
3   1001    10  23065
4   1001    11  19064
5   1001    12  20056
6   1002    10  7011
7   1002    11  20055
8   1002    12  15047
9   1003    12  28149

我上面显示的头部没有显示它,但是有一些用户在特定月份没有拨打电话但使用了数据,所以我必须考虑到这一点,从某种意义上说它不应该忽略这些用户而只是为不可用的数据添加 0。

我应该先对表进行外部联接吗?或者创建一个新表不是正确的方法?任何指导表示赞赏。

谢谢

标签: pythonpandaspandas-groupbypivot-tabledata-wrangling

解决方案


You should merge or join these first, then do the operation. Here I'm doing a left join on internet_per_month (and a call to fillna); if it's possible that someone made calls but not internet, an outer join would be preferable.

df = pd.merge(
    left=internet_per_month, 
    right=calls_per_month, 
    how="left",
    left_on=["user_id", "session_date"], 
    right_on=["user_id", "month"],
)

df.fillna(0)
df["usage"] = df["mb_used"] + df["call_date"]

output:

   user_id  month  call_date  session_date  mb_used    usage
0     1000     12         16            12   2000.0   2016.0
1     1001      8         27             8   7000.0   7027.0
2     1001      9         49             9  14000.0  14049.0
3     1001     10         65            10  23000.0  23065.0
4     1001     11         64            11  19000.0  19064.0
5     1001     12         56            12  20000.0  20056.0
6     1002     10         11            10   7000.0   7011.0
7     1002     11         55            11  20000.0  20055.0
8     1002     12         47            12  15000.0  15047.0
9     1003     12        149            12  28000.0  28149.0

推荐阅读