簡體   English   中英

如何根據另一列值填充空索引或空行?

[英]How to fill empty index or empty row based on another column value?

我有一個數據框:

             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

我的目標是填充空索引行。 非常感謝。

因為有空字符串首先將它們轉換為失蹤的價值觀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

你能試試這個嗎

data.fillna(method='ffill')

得到你想要的輸出。

您可以嘗試使用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)

結果:

             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  

取消分組:

print(df.head(4))

結果:

  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.

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