# 根据条件对多列应用定义 - python

[英]Apply definition on multiple columns based on conditions- python

``````mask = (df['A']=='02')
df.loc[((mask) & (df['B'] !=0)), 'B'] = z_valid['B'].apply(def)
df.loc[((mask) & (df['C'] !=0)), 'C'] = z_valid['C'].apply(def)
df.loc[((mask) & (df['D'] !=0)), 'D'] = z_valid['D'].apply(def)
df.loc[((mask) & (df['E'] !=0)), 'E'] = z_valid['E'].apply(def)
df.loc[((mask) & (df['F'] !=0)), 'F'] = z_valid['F'].apply(def)
``````

``````mask = (df['A']=='02')
df.loc[((mask) & (df['B'] !=0)), 'B'] = z_valid['B'].apply(def)
df.loc[((mask) & (df['C'] !=0)), 'C'] = z_valid['C'].apply(def)
``````

``````df = pd.DataFrame({'A': ['01', '02', '02', '02'], 'B': [9, 1, 2, 3], 'C': [9, 1, 2, 3], 'D': [9, 0, 0, 0]})
print(df)

# Output:
A  B  C  D
0  01  9  9  9
1  02  1  1  0
2  02  2  2  0
3  02  3  3  0
``````

``````def f(sr):
return 2*sr

df.loc[((mask) & (df['B'] !=0)), 'B'] = z_valid['B'].apply(f)
df.loc[((mask) & (df['C'] !=0)), 'C'] = z_valid['C'].apply(f)
df.loc[((mask) & (df['D'] !=0)), 'D'] = z_valid['D'].apply(f)
``````

Output：

``````----> 8 df.loc[((mask) & (df['D'] !=0)), 'D'] = z_valid['D'].apply(f)
...
ValueError: Must have equal len keys and value when setting with an iterable
``````

``````# Left side
>>> df.loc[((mask) & (df['D'] !=0)), 'D']
Series([], Name: E, dtype: int64)  # <- Empty Series

# Right side
>>> z_valid['D'].apply(f)
1    0
2    0
3    0
Name: E, dtype: int64
``````

``````import pandas as pd

df = pd.DataFrame({"x" : ['01', '02', '03', '04', '02', '05', '02'],
"y": [3,3,3,3,3,3,3],
'z': [6,6, 6, 6, 6, 6, 6]
})
cols = ['y', 'z']

def func(x):
return 2*x

df[cols] = df[cols].where(df['x'] != '02', df[cols].applymap(func))

print(df)
``````

``````    x  y   z
0  01  3   6
1  02  6  12
2  03  3   6
3  04  3   6
4  02  6  12
5  05  3   6
6  02  6  12
``````