繁体   English   中英

将 function 应用于 dataframe,索引和列名称为 arguments

[英]Applying a function to dataframe with index and columns names as arguments

考虑一个空的 dataframe (df),其中包含国家作为索引和列状态。

df = pd.DataFrame({'Country': ['Albania', 'France', 'Mexico', 'Russia'], 
                               'On': [0, 0, 0, 0],
                               'Off': [0, 0, 0, 0]}).set_index('Country')

如何将 function 应用于 dataframe 中的每个单元格,索引名称和列名称为 arguments 到 ZCA394125268E16? 我想用可以使它工作的语法替换 row(x) 和 column(x) 。

df = df.apply(lambda x : function(row(x), column(x)))

谢谢

你可以做这样的事情

def fct(row):
    # You can get index with row.name
    print(row.name)
    
    # You can set separately row["On"] and row["Off"]
    print(row["On"])
    print(row["Off"])
    row["On"] = row["On"] + 1
    row["Off"] = row["Off"] + 2
    return row
    
    
dff = df.apply(fct, axis=1)

编辑:如果您确实需要使用依赖于行和列的 function,那么这个解决方案对您有用吗?

def f2(row, col):
    # ...

def fct(row):
    # You can get index with row.name
    row_name = row.name
    for column_name in row.index.values:
        row[v] = f2(row_name, column_name)
    return row
    
    
dff = df.apply(fct, axis=1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM