如何基于另一个列值填充空索引或空行?

问题描述 投票:1回答:3

我有一个数据框:

             Date                Cities       Random_Number
Country
US           2020-01-01          LA           100
             2020-01-03          LA           150
UK           2020-01-01          Ldn          125
             2020-01-03          Birmingham   135

我想要的数据框:

             Date                Cities       Random_Number
Country
US           2020-01-01          LA           100
US           2020-01-03          LA           150
UK           2020-01-01          Ldn          125
UK           2020-01-03          Birmingham   135

我的目标是要填充空的索引行。非常感谢。

python pandas
3个回答
1
投票

因为there are empty strings首先通过Series.mask将它们转换为缺失值,然后通过Series.mask向前填充缺失值:

ffill

0
投票

您可以尝试这个吗?>

df = df.reset_index()
print (df)
  Country        Date      Cities  Random_Number
0      US  2020-01-01          LA            100
1          2020-01-03          LA            150
2      UK  2020-01-01         Ldn            125
3          2020-01-03  Birmingham            135

df['Country'] = df['Country'].mask(df['Country'] == '').ffill()
print (df)
  Country        Date      Cities  Random_Number
0      US  2020-01-01          LA            100
1      US  2020-01-03          LA            150
2      UK  2020-01-01         Ldn            125
3      UK  2020-01-03  Birmingham            135

获得所需的输出。


0
投票

您可以尝试data.fillna(method='ffill') 来“取消分组” DataFrame。

© www.soinside.com 2019 - 2024. All rights reserved.