0

尝试对多个列值使用应用/映射。适用于一列。下面做了一个应用于单个列的示例,需要帮助使注释掉的部分适用于多个列作为输入。

我需要它在同一行但来自不同列的 2 个值作为函数的输入,执行计算,然后将结果放在新列中。如果有一种有效/优化的方式可以使用 apply/map/或两者来做到这一点,请告诉我,谢谢!!!

import numpy as np
import pandas as pd


#gen some data to work with
df = pd.DataFrame({'Col_1': [2, 4, 6, 8],
                   'Col_2': [11, 22, 33, 44],
                   'Col_3': [2, 1, 2, 1]})

#Make new empty col to write to
df[4]=""

#some Function of one variable
def func(a):
    return(a**2)

#applies function itemwise to coll & puts result in new column correctly
df[4] = df['Col_1'].map(func)


"""
#Want Multi Variate version. apply itemwise function (where each item is from different columns), compute, then add to new column  

def func(a,b):
    return(a**2+b**2)

#Take Col_1 value and Col_2 value; run function of multi variables, display result in new column...???
df[4] = df['Col_1']df['Col_2'].map(func(a,b))


"""
4

1 回答 1

1

您可以使用 apply 函数将数据框的每一行作为系列传递。然后在函数本身中你可以根据需要使用它的值。

def func(df): return (df['Col_1']**2+df['Col_2']**2)

df[4] = df.apply(func, axis = 1)

请参考文档进行探索。

于 2020-06-10T12:27:47.633 回答