簡體   English   中英

多個If-else語句結果

[英]Multiple If-else statement results

如何為多個答案而不是條件設置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))

錯誤是:NameError:未定義名稱“ 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'

假設您在熊貓中有以下數據集

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

作為替代df.loc使用哈利勒Hooti可以考慮使用np.where以下列方式

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

在我的實驗中,看起來是更快的解決方案。

更新

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM