Python熊猫-比较值

时间:2020-08-07 07:52:57

标签: python pandas

Input and Expected Output

  1. 如何从下一行复制NaN的值并将标记添加为“(复制)”? 完成-
df = (df.bfill() + df.fillna(' (copy)').where(df.isna())).fillna(df)
  1. 如何将row 2 row 3的值与第1行的值进行比较,如果值不相同并获得预期的输出,如何将string添加为“(不相同)”? ?

1 个答案:

答案 0 :(得分:1)

将掩码保留在变量中,以便以后使用:

df = pd.DataFrame({"col1":[np.NaN,"Cat","Cheese"],
                   "col2":["Dog","Cheese","Dog"],
                   "col3":[np.NaN,"Cat","Dog"]})

copy_mask = df.isnull()

df = df.bfill()

same_mask = df!=df.iloc[0]

df[same_mask]+=" (Not same)"
df[copy_mask]+=" (Copy)"

print (df)

                col1               col2            col3
0         Cat (Copy)                Dog      Cat (Copy)
1                Cat  Cheese (Not same)             Cat
2  Cheese (Not same)                Dog  Dog (Not same)