如何解决如何在完整数据框中应用 def 函数?
我需要帮助来纠正功能。我对两件事感到困惑。
raw_data = {'age1': [23,45,21],'age2': [10,20,50]}
df = pd.DataFrame(raw_data,columns = ['age1','age2'])
df
效果很好。
l = list(df.columns)
for c in l:
df[c]=np.where(df[c]>45,df[c]+100,df[c])
- 它不能正常工作并且增加了超过 100 的值。这里有什么问题。
def fun(x):
l = list(df.columns)
for c in l:
df[c]=np.where(df[c]>45,df[c])
return x
df.apply(fun)
- 为什么我不能在完整的数据帧上应用这个函数。请更正...
def f(x):
val=[]
if x>=40:
val = x+100
else:
val = x
return val
df.apply(f,axis=1)
解决方法
函数做不同的事情。
第一个选项有效,因为您要遍历每一列并将 np.where 应用于每一列一次。
for c in df.columns:
df[c] = np.where(df[c] > 45,df[c] + 100,df[c])
df
:
age1 age2
0 23 10
1 45 20
2 21 150
在这种情况下:
def fun(x):
l = list(df.columns)
for c in l:
df[c]=np.where(df[c]>45,df[c]+100,df[c])
return x
df.apply(fun)
为每一列调用函数 fun
(通过 apply
),但您每次都在执行完整的操作。
这大致相当于:
for _ in df.columns:
for c in df.columns:
df[c] = np.where(df[c] > 45,df[c])
注意嵌套循环。
因此它产生 df
的原因:
age1 age2
0 23 10
1 45 20
2 21 250
最后一个选项关闭:
def f(x):
val=[]
if x>=40:
val = x+100
else:
val = x
return val
df.apply(f,axis=1)
然而,x 是一系列值(DataFrame 列),这意味着 x >= 40
不起作用导致错误:
ValueError: The truth value of a Series is ambiguous.
Use a.empty,a.bool(),a.item(),a.any() or a.all().
并且可以稍微修改以使用 applymap
将函数应用于 DataFrame 中的每个单元格:
def f(x):
if x > 45: # Changed the bound to match the np.where condition
val = x + 100
else:
val = x
return val
df = df.applymap(f)
df
:
age1 age2
0 23 10
1 45 20
2 21 150
然而,这里更多的熊猫方法是使用类似 DataFrame.mask
的东西:
df = df.mask(df > 45,df + 100)
df
:
age1 age2
0 23 10
1 45 20
2 21 150
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。