【问题标题】:Fill column in pandas based on prior row data until change根据先前的行数据填充 pandas 中的列,直到更改
【发布时间】:2020-05-30 16:45:40
【问题描述】:

我有一个数据框:

df = pd.DataFrame({'player':['John Adams', 'Mark Capone', 'Cecil Milton', 'Hector James', 'Hector James', 'Luke Valentine', 'Luke Valentine'] , 'action':['Starts at PG', 'Dribbles', 'Passes', 'receives pass', 'Travels', 'Subs in at PG', 'Passes']})

第一列是播放器。第二列是玩家采取的行动。

我想创建第三列来跟踪谁在 PG。我添加列:

df['PG'] = " "

然后我编写以下内容以使用播放器的名称填充 PG 列:

df.loc[(df.action == '从 PG 开始'), 'PG'] = df['player']

df.loc[(df.action == 'Subs in at PG'), 'PG'] = df['player']

我无法弄清楚的问题是如何向前填充 PG 列,直到它在第 5 行被更改,然后用新值从 5 填充到末尾。我以前在数字列上使用过 ffill ,但这是不同的,因为它是我正在使用的字符串。任何帮助是极大的赞赏。

为了清楚起见,我试图在第 0 到第 4 行的 PG 列中获取“John Adams”,在第 5 和第 6 行获取“Luke Valentine”。

【问题讨论】:

    标签: pandas


    【解决方案1】:

    试试ffill,意思是forward fill所有nan值:

     df['PG'] = df.player.where(df.action.str.contains('PG')).ffill()
    

    输出:

               player         action              PG
    0      John Adams   Starts at PG      John Adams
    1     Mark Capone       Dribbles      John Adams
    2    Cecil Milton         Passes      John Adams
    3    Hector James  receives pass      John Adams
    4    Hector James        Travels      John Adams
    5  Luke Valentine  Subs in at PG  Luke Valentine
    6  Luke Valentine         Passes  Luke Valentine
    

    【讨论】:

    • 谢谢。我不确定它到底是什么/如何工作,但它正在工作。太棒了,我整个上午都在为此苦苦挣扎。
    • 如果你想知道它是如何工作的,打印df.action.str.contains('PG'),然后打印df.player.where(df.action.str.contains('PG'))?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-04
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多