在Python的if语句内调用函数

时间:2019-11-16 19:17:31

标签: python-3.x pandas

我有一个如下的pandas数据框。我有一个将C和D的值更新为-99的函数。

def func(df):
    for col in df.columns:
        if ("C" in col) or ("D" in col):
            df.loc[:,col] = -99

现在,如果A = 2,我只想调用该函数。我尝试了以下代码,但它将C和D的所有行更新为-99

import pandas as pd
data=[[0,1,0,0, 0],
      [1,2,0,0,0],
      [2,0,0,0,0],
      [2,4,0,0,0],
      [1,8,0,0,0],
      [3,2, 0,0,0]]

df = pd.DataFrame(data,columns=['A','B','C', 'D','E'])
df
def func(df):
    for col in df.columns:
        if ("C" in col) or ("D" in col):
            df.loc[:,col] = -99

if (df['A'] == 2).any():
    func(df)
    print(df)

我的预期输出:

   A  B   C   D  E
0  0  1  0   0  0
1  1  2  0   0  0
2  2  0 -99 -99  0
3  2  4 -99 -99  0
4  1  8  0   0  0
5  3  2  0   0  0

1 个答案:

答案 0 :(得分:0)

您可以尝试一下,

>>> import pandas as pd
>>> data=[[0,1,0,0, 0],
      [1,2,0,0,0],
      [2,0,0,0,0],
      [2,4,0,0,0],
      [1,8,0,0,0],
      [3,2, 0,0,0]]... ... ... ... ...
>>> df = pd.DataFrame(data,columns=['A','B','C', 'D','E'])
>>> df.loc[df.A == 2, ['C', 'D']] = -99
>>> df
   A  B   C   D  E
0  0  1   0   0  0
1  1  2   0   0  0
2  2  0 -99 -99  0
3  2  4 -99 -99  0
4  1  8   0   0  0
5  3  2   0   0  0

或者您要调用函数,

import pandas as pd
data=[[0,1,0,0, 0],
      [1,2,0,0,0],
      [2,0,0,0,0],
      [2,4,0,0,0],
      [1,8,0,0,0],
      [3,2, 0,0,0]]

df = pd.DataFrame(data,columns=['A','B','C', 'D','E'])
df
def func(df, condition):
    for col in df.columns:
        if col in ['C', 'D']:
            df.loc[condition, col] = -99

condition = df['A'] == 2

if condition.any():
    func(df, condition)
    print(df)

此处输出:

   A  B   C   D  E
0  0  1   0   0  0
1  1  2   0   0  0
2  2  0 -99 -99  0
3  2  4 -99 -99  0
4  1  8   0   0  0
5  3  2   0   0  0