参考
在对dataframe进行运算的过程中会遇到需要根据其他列的条件来更新当前列的数值这种情况,方式如下:
import pandas as pd
df = pd.Dataframe()
def get_c(index1, index2):
if index1 == 1 and index2 ==1:
return 1
return 0
df["A"] = [1, 1, 1, 0, 0, 0, 1]
df["B"] = [0, 1, 1, 0, 0, 1, 1]
df["C"] = [0, 1, 0, 0, 0, 0, 1]
# 若AB均为1,C才为1,其他情况下C必须为0
df["C"] = df.apply(lambda x: get_c(x.A, x.B), axis=1)
print(df["C"].tolist())
# [0, 1, 1, 0, 0, 0, 1]
# 也可以根据此方式新建一列
df["D"] = df.apply(lambda x: get_c(x.B, x.C), axis=1)
还有一些情况是定位到具体位置,然后对该位置的进行赋值/元素替换
# 根据条件定位所在的行
col_ind = df.loc[df["C"] == 1].index
# 对符合条件的行对应B字段进行替换/赋值
source.loc[col_ind, "B"] = 2