熊猫使用基于第二列的另一列方法替换NaN

Ivo*_*Ivo 3 python pandas

我有一个带有两列的熊猫数据框,city和country。双方city并country包含缺失值。考虑以下数据帧:

temp = pd.DataFrame({"country": ["country A", "country A", "country A", "country A", "country B","country B","country B","country B", "country C", "country C", "country C", "country C"],
                     "city": ["city 1", "city 2", np.nan, "city 2", "city 3", "city 3", np.nan, "city 4", "city 5", np.nan, np.nan, "city 6"]})
Run Code Online (Sandbox Code Playgroud)

我现在想在填写NaN在S city与列模式该国在剩余的数据帧的城市,例如对于A国:城市1被提及一次; 提到城市2两次;因此,用etc 填充city索引处的列。2city 2

我已经做好了

cities = [city for city in temp["country"].value_counts().index]
modes = temp.groupby(["country"]).agg(pd.Series.mode)
dict_locations = modes.to_dict(orient="index")
for k in dict_locations.keys():
     new_dict_locations[k] = dict_locations[k]["city"]
Run Code Online (Sandbox Code Playgroud)

现在有了国家的价值和相应的城市模式,我面临两个问题:

第一:案例country C是双峰的-密钥包含两个条目。我希望此键以相等的概率引用每个条目。实际数据集具有多种模式,因此它将是len> 2的列表。

第二:我一直坚持用NaNs 替换为city与中同一行country单元格中的值相对应的值new_dict_locations。用伪代码,这将是:`遍历'city'列;如果在“ temp [i,city]”位置找不到值,请在该行中获取“ country”的值(->“ country_tmp”);将“ country_tmp”作为字典“ new_dict_locations”的键;如果键“ country_temp”处的字典是列表,则从该列表中随机选择一项;取返回值(->'city_tmp'),并用值为'city_temp'的缺失值(temp [i,city])填充单元格。

我使用的不同组合尝试.fillna()和.replace()(读这个问题和其他问题无济于事。*有人可以给我一个指针?

提前谢谢了。

(注意:所引用的问题会根据字典替换一个单元格中的值;但是,我的引用值在另一列中。)

**编辑**执行temp["city"].fillna(temp['country'], inplace=True)并temp.replace({'city': dict_locations})给我一个错误:TypeError: unhashable type: 'dict'[此错误是TypeError: unhashable type: 'numpy.ndarray'针对原始数据集的,但我无法通过示例进行重现-如果有人知道差异的所在,我将非常高兴听到他们的想法。 ]

And*_* L. 5

尝试map用字典new_dict_locations来创建一个新的系列s,并重新映射s与np.random.choice从阵列挑值。最后,使用s来fillna

s = (temp.country.map(new_dict_locations)
                 .map(lambda x: np.random.choice(x) if isinstance(x, np.ndarray) else x))

temp['city'] = temp.city.fillna(s)    

Out[247]:
      country    city
0   country A  city 1
1   country A  city 2
2   country A  city 2
3   country A  city 2
4   country B  city 3
5   country B  city 3
6   country B  city 3
7   country B  city 4
8   country C  city 5
9   country C  city 6
10  country C  city 5
11  country C  city 6
Run Code Online (Sandbox Code Playgroud)

注意:我认为2map通过使用dict理解可以合并为一个。但是,这样做会导致随机性的降低。