[英]How to fill empty index or empty row based on another column value?
I have a data frame:我有一个数据框:
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
My desired data frame:我想要的数据框:
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
My aim is to have empty index row to be filled.我的目标是填充空索引行。 Many thanks.非常感谢。
Because there are empty strings first convert them to missing values by Series.mask
and then forward filling missing values by ffill
:因为有空字符串首先将它们转换为失踪的价值观Series.mask
再往前填充缺失值ffill
:
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
can you try this你能试试这个吗
data.fillna(method='ffill')
Got your desired output.得到你想要的输出。
You can try df.head(4)
to 'ungroup' the DataFrame.您可以尝试使用df.head(4)
来“取消分组”DataFrame。
df = pd.DataFrame([['US', '2020-01-01', 'LA', 100],
['US', '2020-01-03', 'LA', 150],
['UK', '2020-01-01', 'Ldn', 125],
['UK', '2020-01-03', 'Birmingham', 135]],
columns=['Country', 'Date', 'Cities', 'Random_Number']).groupby('Country')
print(df)
Result:结果:
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
Ungroup:取消分组:
print(df.head(4))
Result:结果:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.