当值与另一列匹配时,回填 Pandas 系列中的值 [英] Backfill values in Pandas series when value matches another column

查看:68
本文介绍了当值与另一列匹配时,回填 Pandas 系列中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的 DataFrame:

I have a DataFrame like this:

import numpy as np

raw_data = {'surface': [np.nan, np.nan, 'round', 'square'],
            'city': ['San Francisco', 'Miami', 'San Francisco', 'Miami']}

df = pd.DataFrame(raw_data, columns = ['surface', 'city'])

看起来像这样:

        surface city
   0    NaN     San Francisco
   1    NaN     Miami
   2    round   San Francisco
   3    square  Miami

我需要用圆形"填充旧金山行的最早实例,用方形"填充较早的迈阿密行.使用 .fillna(method='bfill') 不会考虑其他列值,只会用圆形填充所有较早的行.

I need earliest instance of the San Francisco row to be filled with 'round', and the earlier Miami row to be filled with 'square'. Using .fillna(method='bfill') won't take into account other column values, and just fills all earlier rows with round.

结果是:

        surface city
   0    round   San Francisco
   1    square  Miami
   2    round   San Francisco
   3    square  Miami

推荐答案

您可以使用 groupby.bfill;按 city 列对数据框进行分组,然后使用 bfill:

You can use groupby.bfill; group data frame by city column and then use bfill:

df.groupby('city').bfill()

#  surface           city
#0  round   San Francisco
#1  square          Miami
#2  round   San Francisco
#3  square          Miami

这篇关于当值与另一列匹配时,回填 Pandas 系列中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆