如何填充(向前填充)Pandas中的过滤 Dataframe 列

nnvyjq4y  于 2023-08-07  发布在  其他
关注(0)|答案(3)|浏览(163)

问题陈述:需要填充已过滤的 Dataframe 。
我有一个大的 Dataframe 。它没有显示在这里,但我已经包括了一个虚拟的 Dataframe 作为一个例子如下。
我需要的状态/状况组合只有UP/GOOD和DOWN/BAD。
我的数据集目前有不需要的DOWN/GOOD组合,我试图通过填充过滤的 Dataframe 将其更正为DOWN/BAD。请对下面的代码提出建议,它不起作用。有几个其他的解决方案可以解决这个问题,但我喜欢filldown(. ffill)方法。
谢谢!
未筛选的数据集

过滤数据集:显示关闭状态

理想解决方案

代码:

"""This is a dummy dataframe"""
import pandas as pd
import numpy as np
dummydata=[["Up","Good"],["Up","Good"],["Up","Good"],["Down","Bad"],["Up","Good"],
           ["Down","Good"],["Down","Good"],["Down","Good"],["Up","Good"],["Up","Good"],
           ["Down","Bad"],["Up","Good"],["Up","Good"],["Up","Good"],["Up","Good"]]
df=pd.DataFrame(dummydata, columns=['Status','State'])
filt=df['Status']=="Down"
df2=df.loc[filt]
df2.loc[df2['State']=='Good','State']=""
df2.loc[df2.State=='','State']= np.nan
df2.loc[df2['State']=='','State']=df2['State'].ffill()
print(df,df2)

我目前的filldown方法不工作。代码提供。任何帮助将不胜感激

iqxoj9l9

iqxoj9l91#

这里没有必要切片。
最简单的方法是:

df2['State'] = df2['State'].replace('Good', np.nan).ffill()

输出:

Status State
3    Down   Bad
5    Down   Bad
6    Down   Bad
7    Down   Bad
10   Down   Bad
abithluo

abithluo2#

使用此:

df.loc[df['Status']=='Down','State']='Bad'
df[df['Status']=='Down']

   Status State
3    Down   Bad
5    Down   Bad
6    Down   Bad
7    Down   Bad
10   Down   Bad
mftmpeh8

mftmpeh83#

用户可以直接使用条件过滤并分配。

    • 代码:**
import pandas as pd
import numpy as np
dummydata=[["Up","Good"],["Up","Good"],["Up","Good"],["Down","Bad"],["Up","Good"],
        ["Down","Good"],["Down","Good"],["Down","Good"],["Up","Good"],["Up","Good"],
        ["Down","Bad"],["Up","Good"],["Up","Good"],["Up","Good"],["Up","Good"]]
df=pd.DataFrame(dummydata, columns=['Status','State'])
#Filter Status == Down and State == Good
df.loc[((df["Status"] == "Down") &  (df["State"] =="Good")), "State"] = "Bad"

相关问题