【问题标题】:Using nested apply: apply for each row in each column使用嵌套应用:对每一列中的每一行应用
【发布时间】:2020-11-22 02:18:24
【问题描述】:

我想为数据框中的所有列转换每一行。

所以我的数据集看起来像:

df = pd.DataFrame({'col1': [100,100,100,100],
        'col2': [100,100,100,100],
        'col3': [100,100,100,100]
        })
df.index=pd.date_range('2018-01-01', periods=4, freq='D')

我要应用的函数使用索引和列名作为输入参数并返回一个转换。 一个例子是:

def apply_fct(row):
    
    # since row is a series, .name delivers rowname and .index the colname
    out=row[0] * row.name.day + row.index.values[0][-1]

    return(out)

因此,将此功能应用于一列可以正常使用:

df['col2'].to_frame().apply(apply_fct,axis=1)

但是,我需要将其应用于所有列。

由于列数和名称是可变的,我需要一种更灵活的方法。 我考虑过嵌套应用 - 但我被卡住了。 希望循环不是唯一的选择。

【问题讨论】:

    标签: python apply


    【解决方案1】:

    你想确保你的函数输出一个系列,然后你对整个数据框使用 apply

    import pandas as pd
    
    df = pd.DataFrame({'col1': [100,100,100,100],
        'col2': [100,100,100,100],
        'col3': [100,100,100,100]
        })
    df.index=pd.date_range('2018-01-01', periods=4, freq='D')
    
    def apply_fct(row):
    out =(row * row.name.day).astype(str)+pd.Series(row.index,index=row.index)   
    return(out)
    
    df=df.apply(apply_fct,axis=1)
    
    print(df)
    

    输出:

                col1     col2     col3
    2018-01-01  100col1  100col2  100col3
    2018-01-02  200col1  200col2  200col3
    2018-01-03  300col1  300col2  300col3
    2018-01-04  400col1  400col2  400col3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-23
      相关资源
      最近更新 更多