簡體   English   中英

Pandas:設置 dataframe 的一列的值,條件是另一個 dataframe 的另一列

[英]Pandas: set the value of one column of a dataframe with condition on another column of another dataframe

我有兩個數據框 df1 和 df2,每列有兩列:

df1                                            df2
c1 c2                                          c2 c3

我想為 df1 創建一個新列 c3,它將是:

  • 當 df1.c2 = df2.c2 時,等於 df2 的 c3 列
  • 其他 NaN

這基本上就是 vlookup function 在 Excel 中所做的事情。

到目前為止,我已經嘗試過:

df1["c3"] = np.nan

for i in df1.c2.unique():
    for j in df2.c2.unique():
        if i == j:
            df1.loc(df1.c2 == i, "c3") = df2.loc(df2.c2 == j, "c3")
        else:
            pass
        

但是當我打印結果df1時, c3保持不變......我通過在循環中分別打印它們來檢查我的df1.locdf2.loc ,它們都瞄准了正確的值......

誰能幫我解決這個問題?

PS:為了進一步了解,我正在嘗試將 pygal 國家代碼與相應的國家/地區相關聯,以便在世界 map 中將它們 plot。

df1 = my dataset

df1.c1 = relavant data

df1.c2 = country name

df1.c3 = country code

df2 = pygal country code table

df2.c2 = country name

df2.c3 = country code
        

NumPy np.where()這樣的東西:

df1['c3'] = np.where(df1['c2'] == df2['c2'], df2['c3'], np.nan)

有點像 Excel 中的if()

暫無
暫無

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

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