简体   繁体   English

如何从另一列及以上行中的值填充 pandas dataframe 中的 nan 值?

[英]How to fill nan value in pandas dataframe from value in another column and above row?

I have df as follows:我有 df 如下:

df = pd.DataFrame({"A":[0,np.nan,0,0,np.nan,1,np.nan,1,0,np.nan],
                   "B":[0,1,0,0,1,1,1,0,0,0]})

Now, I need to replace nan values in column A with values from column B and one above row.现在,我需要将 A 列中的 nan 值替换为 B 列和上一行的值。 for example: 2nd row for column A should be 0, 7th row equals to 1 etc.例如:A 列的第 2 行应为 0,第 7 行应为 1,依此类推。

I defined this function but it doesnt work trying to apply into dataframe我定义了这个 function 但它无法尝试应用于 dataframe

def impute_with_previous_B(df):
    for x in range(len(df)):
        if pd.isnull(df.loc[x,"A"]) == True:
            df.loc[x,"A"] = df.loc[x-1,"B"]

df["A"] = df.apply(lambda x: impute_with_previous_B(x),axis=1)

Can you please tell me what is wrong with that function?你能告诉我那个function有什么问题吗?

df['A'] = df['A'].fillna(df['B'].shift())


     A  B
0  0.0  0
1  0.0  1
2  0.0  0
3  0.0  0
4  0.0  1
5  1.0  1
6  1.0  1
7  1.0  0
8  0.0  0
9  0.0  0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当同一行中的另一列为NaN时,如何从熊猫数据框中选择特定的列值? - How to select a particular column value from a pandas dataframe when another column in the same row is NaN? 使用来自另一个DataFrame熊猫的随机值填充nan值 - Fill nan values with random value from another DataFrame pandas 当列值匹配时,Pandas Dataframe会从行中替换Nan - Pandas Dataframe replace Nan from a row when a column value matches 如果另一列的值匹配,如何在列中填充 nan 值 - How to fill nan values in a column if the value from another column matches 如何使用来自另一个 dataframe 列的值填充 pandas dataframe 列 - How to fill a pandas dataframe column using a value from another dataframe column 根据熊猫中的行匹配,用另一个DataFrame中的值有条件地填充列 - Conditionally fill column with value from another DataFrame based on row match in Pandas 如何根据另一列填充 nan 值 - how to fill nan value based on another column 用必须在另一列的特定行上计算的公式填充值为0或NaN的Pandas数据框行 - Fill Pandas dataframe rows, whose value is a 0 or NaN, with a formula that have to be calculated on specific rows of another column 通过从其他DataFrame中选择值,在Pandas DataFrame中填充NaN - Fill NaN in Pandas DataFrame by selecting value from other DataFrame Python/Pandas:如果值为 NaN 或 0,则用同一行内下一列的值填充 - Python/Pandas: if value is NaN or 0 then fill with the value from the next column within the same row
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM