我正在尝试创建一个数据帧。
df = pd.DataFrame(columns=["Year", "Fuel", "Status", "Sex", "Service", "Expected"])
其他列包含使用np.random
创建的数据。
在"预期"列中,我想根据一些条件输入通过或失败。如果里程数小于 100000,并且服务是肯定的,那么它将通过,否则就是失败。
这就是我到目前为止所拥有的
df["Expected"] = df.loc[(df['Mileage']< 100000) | (df['Service'] == 'Yes', "Pass", "Fail")]
它正在显示错误消息
ValueError: operands could not be broadcast together with shapes (500,) (3,)
我已经用 500 行数据填充了其他列。但我不确定这 3 与什么有关。可能是"是"、"通过"、"失败"值。
我也尝试df['Expected'] = np.where(df ["Mileage"] < 132352, ['Service'] == "Yes",'Pass','Fail')
哪种有效。
我是不是走错了路?
任何帮助或指示将不胜感激。
我会创建一个函数,该函数将pd.Series
对象作为唯一的参数,然后返回该单元格的值。然后使用pd.apply(lambda row: your_function(row), axis=1)
.所以:
def your_function(row):
if row["Mileage"] <132352 and row["Service"] == "Yes" :# fill in your other conditions here
return "Pass"
else:
return "Fail"
df["Expected"] = df.apply(lambda row: your_function(row), axis=1)
您可以简单地用'Fail'
填充Expected
列:
df['Expected'] = 'Fail'
然后:
df.at[df[(df['Mileage']<100000) & (df['Service'] == 'Yes')].index,'Expected'] = 'Pass'