多个Ifelse语句结果

2024-04-25 15:21:21 发布

您现在位置:Python中文网/ 问答频道 /正文

如何为多个答案而不是条件设置if语句?你知道吗

所以在我的例子中,我想说如果i等于0,那么ab将有唯一的答案。你知道吗

df is a dataframe something like:

0 d 8
0 d 9
0 t 7
1 q 7
0 u 8
0 r 5
1 s 3

for c in range(len(df.index)):
    for i in df.iloc[[c]],0]:
        if i == 0:
            a = 12
            b = 'up'
OUT.write('%i,%s,'%(a,b))

错误为:名称错误:未定义名称“a”

我试过:

for c in range(len(df.index)):
    for i in df.iloc[[c]],0]:
        if i == 0:
            a = 12; b = 'up'

以及

for c in range(len(df.index)):
    for i in df.iloc[[c]],0]:
        if i == 0:
            a = 12 and b = 'up'

Tags: 答案in名称dfforindexlenif
2条回答

假设您在pandas中有以下数据集

import pandas as pd
import numpy as np
df = pd.DataFrame(columns=['variable', 'a', 'b'])
df.variable = np.random.choice(range(5), size=10)

print(df)

输出如下:

  variable   a   b
0   0   NaN NaN
1   4   NaN NaN
2   0   NaN NaN
3   3   NaN NaN
4   4   NaN NaN
5   0   NaN NaN
6   3   NaN NaN
7   3   NaN NaN
8   4   NaN NaN
9   0   NaN NaN

现在您可以按如下方式更改“a”和“b”中的项

df.loc[df.variable == 0, 'a'] = 12
df.loc[df.variable == 0, 'b'] = "up"
print(df)

输出:

    variable    a   b
0   0   12  up
1   4   NaN NaN
2   0   12  up
3   3   NaN NaN
4   4   NaN NaN
5   0   12  up
6   3   NaN NaN
7   3   NaN NaN
8   4   NaN NaN
9   0   12  up

作为Khalil Al Hooti使用df.loc的替代方法,您可以考虑按以下方式使用np.where

df["a"] = np.where(df.variable==0, 12, df["a"])
df["b"] = np.where(df.variable==0, "up", df["a"])

在我的实验中,似乎有一个更快的解决方案。你知道吗

更新

enter image description here

相关问题 更多 >