如何为每一行分别运行函数(python)?

2024-10-16 17:15:51 发布

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

我有以下功能:

def match_function(df):

    columns = df.columns.tolist()
    matches = {}

    for column in columns:
        df = df.astype(str)
        df_new = df.dropna()
        df_new = df[column].str.split(',', expand=True)
        df_new = df_new.apply(lambda s: s.value_counts(), axis=1).fillna(0)
        match = df_new.iloc[:, 0][0] / df_new.sum(axis=1) * 100
        match = round(match, 2)

        df[column] = match
        matches[column] = match

    return matches

我希望这个函数对数据帧的每一行完全单独运行。它将循环通过数据帧的第一行,然后停止并再次运行第二行,以此类推

因为它是以一种非常复杂和不专业的方式编写的(因为我是Python新手),当我传递一个数据帧并且它同时在整个数据帧中运行时,结果是错误的。 或者可能会以某种方式更改函数本身,使其只能一行一行地运行


Tags: columns数据函数功能dfnewdefmatch
1条回答
网友
1楼 · 发布于 2024-10-16 17:15:51

考虑下面的DF:

          a         b
0  1.000000  0.000000
1 -2.000000  1.000000
2  1.000000  0.000000
3  3.000000 -4.000000

以及下面的函数"func"

def func(x):    
   return x['a'] + x['b'] 

您可以通过以下方式在行的基础上应用该函数:

df.apply(func, axis=1)

比产量:

0    1.000000
1   -1.000000
2    1.000000
3   -1.000000

因此,基本上,对于每一行,我们都应用了命名函数func(),即x['a']+ x['b']

相关问题 更多 >