簡體   English   中英

替換與另一列 pandas 中的特定值相對應的列中的空值

[英]Replace null values in a column corresponding to specific value in another column pandas

我有一個如下的數據框:

import pandas as pd
df = pd.DataFrame({'Country': ['USA','USA','MEX','IND','UK','UK','UK'],
                   'Region': ['Americas','NaN','NaN','Asia','Europe','NaN','NaN'],
                   'Flower': ['Rose','Lily','Lily','Orchid','Petunia','Lotus','Dandelion']})

我想用其他區域的值替換 Region 中的NaN值。 我的意思是,如果國家是美國或墨西哥,地區應該是美洲,如果國家是英國,地區應該是歐洲。

預期的輸出是

result = pd.DataFrame({'Country': ['USA','USA','MEX','IND','UK','UK','UK'],
                       'Region': ['Americas','Americas','Americas','Asia','Europe','Europe','Europe'],
                       'Flower': ['Rose','Lily','Lily','Orchid','Petunia','Lotus','Dandelion']})

我想知道一種簡單的方法,而不必編寫 if else 語句。

如果 ffill 不是一個選項,您可以嘗試以下代碼,

df['Region'] = np.select((df.Country.isin(['USA', 'MEX']), df.Country == 'UK'),
                         ('Americas', 'Europe'), df.Region) 

暫無
暫無

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

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