在python中将过程应用于数据帧中的某些行

2024-10-04 09:26:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧。我想对所选行应用一个函数。最终的想法是根据一些并行化方案选择行

假设a有一个名为“dfr”的数据帧。我还将函数定义为:

def test(xx):
    
    print(xx)
    
    return

我想对数据帧的每一行应用测试,例如,我可以使用:

dfr.apply(test, axis=1)

但是,如何对第5行和第15行之间的所有行执行此操作

我试过“lambda”,但似乎不起作用

谢谢你的帮助


Tags: 数据lambda函数testreturn定义def方案
2条回答

IIUC:

dfr.iloc[5:15].apply(test, axis = 1)

^{}允许您根据行(和列)的位置选择行(和列)

您可以为数据帧创建只有特定行的筛选副本,然后在该筛选副本上运行apply或lambda。然后在原始索引上合并以获得输出。您需要决定如何处理行的空值,您没有做任何事情来覆盖原始列吗?请注意,apply和lambda的速度很慢,所以如果您可以避免它,您会过得更好。过滤df可以减少lambda需要做的工作量

def test(xx):
    return xx + 1

df = pd.DataFrame({'values':[i for i in range(20)]})

df_filtered = df.iloc[6:15, :]  
# For slicing rows explicitly, from 6 up to but not including 15

df_filtered = df_filtered.apply(test, axis=1)

df_filtered = df_filtered.rename(columns={'values':'new_values'})
df = df.join(df_filtered)       # joins on original index

相关问题 更多 >