【问题标题】:How to execute a function on a group of rows in pandas dataframe and concatenate the results row wise on axis 0?如何在 pandas 数据框中的一组行上执行一个函数并在轴 0 上逐行连接结果?
【发布时间】:2022-12-19 15:12:52
【问题描述】:

我有一个如下所示的 DataFrame:

cell_id   col1   col2 

en_1  2.0   3.0
en_2  8.0   9.0
.
.
en_2  9.0   8.0  
en_1  9.0   8.0   
.
.
en_n  4.0   6.7

我想一次将每个 cell_id 的这个 DataFrame 发送到下面的某个函数,并按行连接结果(轴 0)

 def func(df):
     do_some_process
     return df

result1 = func(df[df.cell_id.eq('en_1')])
result2 = func(df[df.cell_id.eq('en_2')])
.
.
result_n = func(df[df.cell_id.eq('en_n')])

result = pd.concat([result1, result2,.....,result_n], axis=0)   

【问题讨论】:

  • 你能提供函数的例子吗?

标签: python pandas dataframe


【解决方案1】:

您可以简单地使用df.apply(),如下所示:

def func(x):
    #perform your operation on the pd.Series
    return x

df.apply(func, axis=1)

【讨论】:

    猜你喜欢
    • 2020-05-24
    • 2019-04-16
    • 2018-01-18
    • 2015-09-09
    • 2020-08-04
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    • 2019-07-03
    相关资源
    最近更新 更多