pandas 基于条件在多个列上应用定义- python

dddzy1tm  于 2023-06-20  发布在  Python
关注(0)|答案(2)|浏览(116)

当一个等于'02'的列将定义应用到其他5列时,我有我想要的dataframe。这是我的代码:

mask = (df['A']=='02')
z_valid = df[mask]
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)

我得到了这个错误:'ValueError:设置时必须具有相等的len键和value
但是当我只在2列上应用def时,这段代码可以工作:

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

我如何修复这个错误?先谢谢你。

xv8emn3q

xv8emn3q1#

它引发了一个异常,因为'D'是一个空的Series
假设下面的dataframe:

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

mask = (df['A']=='02')
z_valid = df[mask]
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)

输出:

----> 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

在'D'上引发异常:

# 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
b0zn9rqh

b0zn9rqh2#

如果我理解了需求,你可以像下面的例子一样使用.where.applymap

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

相关问题