python - 如何使用Python中另一列的值填充pandas数据框中的空值?

标签 python pandas

我需要根据Country列填充City列中的空值。如果国家/地区相同,则应使用该国家/地区对应的常用城市名称填充 NaN 值。

输入:

ID      City            Country
0       New York            USA
1            NaN            USA
2         London            UK
3         Mumbai            IND
4         Sydney            AUS
5            NaN            AUS
6         Sydney            AUS
7         Brisbane          AUS

输出:

ID      City            Country
0       New York            USA
1       New York            USA
2         London            UK
3         Mumbai            IND
4         Sydney            AUS
5         Sydney            AUS
6         Sydney            AUS
7         Brisbane          AUS

最佳答案

想法是将可能的空字符串替换为 NaN,然后​​用第一个非 NaN 值替换组的值:

df['City'] = (df.groupby('Country')['City']
                .transform('first'))

或者向前和向后填充缺失值:

df['City'] = (df.groupby('Country')['City']
                .transform(lambda x: x.ffill().bfill()))

关于python - 如何使用Python中另一列的值填充pandas数据框中的空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70113335/

相关文章:

python - 为每组行按行迭代的最有效方法是什么?

python - 以编程方式将 kml 转换为图像

python - 从 args 动态设置 pytest fixture 的范围

python - 通过TCP从arduino发送数据到python

python - Python Pandas 中的引擎 read_csv

python - 没有迭代的两个数据帧的交集

python - 分页在 ListView 中不显示页码

Python 间隔三角形

python - DataFrame 有条件地组合列

python - Pandas 对重复索引求和