簡體   English   中英

Python pandas:根據條件從多個數據框中訪問數據

[英]Python pandas: Accessing data from multiple data frame based on condition

我必須計算一個指標,該指標要求我從多個列中查找同一“用戶”的屬性。 例如,我有兩個數據框如下所示:

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。

我應該首先對表進行外部聯接嗎? 或者創建一個新表不是正確的方法嗎? 任何指導表示贊賞。

謝謝

您應該先合並或加入這些,然后再進行操作。 在這里,我在internet_per_month上進行left join (並調用fillna ); 如果有人撥打電話但無法上網,則最好使用外部連接。

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"]

輸出:

   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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM