我需要清理数据框中的许多列;因此,我通过dataframe列上的apply方法定义并使用了多个函数
一个虚构的例子:
def fn_a(x):
if x<50:
return 'OK'
else:
return 'not OK'
def fn_b(x):
if x<=40:
return 'too small'
elif x>40 and x<70:
return 'just right'
else:
return 'too high'
df = pd.DataFrame(np.random.randint(0, 100, size=(5, 2)), columns=['a','b'])
df['a'] = df['a'].apply(fn_a)
df['b'] = df['b'].apply(fn_b)
是否有一种方法可以只应用一个函数,即定义一个fn()
函数并将其传递到apply方法,而不是逐列传递?换句话说,我应该在fn
中添加什么
def fn(x):
...
df = df.apply(fn)
够了吗
可复制数据:
使用熊猫应用:
如果确实要使用apply进行此操作,可以设置
axis=1
并使用x[colname]
检索列名,其中x
是当前行:输出:
使用矢量化方法:
可以考虑使用^{} 和^{} 。另外,看看^{} 。您可以设置一个函数来更新数据帧就地:
输出:
如果不想在位置中修改数据帧,请在函数中进行复制,修改复制的数据帧,然后返回:
返回相同的输出
尝试:
相关问题 更多 >
编程相关推荐