我是熊猫的新手。想知道如何将函数应用于数据帧中的两列,并将函数的输出映射到数据帧中的新列。这是否可能使用pandas语法,或者我应该求助于本机Python来迭代数据帧列中的行以生成新列?
a b
1 2
3 1
2 9
问题是如何获得,例如,在新列c中两个数字的乘法
a b c
1 2 2
3 1 3
2 9 18
你可以用熊猫。
例如:
def funcMul(row):
return row['a']*row['b']
然后
df['c'] = df.apply(funcMul,1)
输出:
a b c
0 1 2 2
1 3 1 3
2 2 9 18
你可以用熊猫做以下事情
import pandas as pd
def func(r):
return r[0]*r[1]
df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})
df['c'] = df.apply(func, axis = 1)
另外,这是官方文档 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html
harvpan 的评论显示了实现特定示例的最简单方法,但这里有一种通用的方法来完成您的要求:
def functionUsedInApply(row):
""" The function logic for the apply function comes here.
row: A Pandas Series containing the a row in df.
"""
return row['a'] * row['b']
def functionUsedInMap(value):
""" This function is used in the map after the apply.
For this example, if the value is larger than 5,
return the cube, otherwise, return the square.
value: a value of whatever type is returned by functionUsedInApply.
"""
if value > 5:
return value**3
else:
return value**2
df['new_column_name'] = df.apply(functionUsedInApply,axis=1).map(functionUsedInMap)
上面的函数首先将列 a 和 b 相加,然后返回 a+b <=5 时该值的平方和 a+b> 5 值的立方体。