[英]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.