我知道如何在数据帧上使用 apply 函数来计算新列并将它们附加到数据帧。我的问题是,如果我有一个函数,它接受多个值(对应于当前数据框中的列)并返回一个字典(对应于我想要添加到数据框中的列)作为参数,是否有一种简单/优雅的方法将此函数应用于数据框并生成新列?
例如,目前我正在这样做:
import pandas as pd
import numpy as np
col1 = [np.random.randn()] * 10
col2 = [np.random.randn()] * 10
col3 = [np.random.randn()] * 10
df = pd.DataFrame({'col1': col1,
'col2': col2,
'col3': col3 })
df['col4'] = df.apply(lambda x: get_col4(x['col1'], x['col2']), axis=1)
df['col5'] = df.apply(lambda x: get_col5(x['col1'], x['col2'], x['col3']),
axis=1)
df['col6'] = df.apply(lambda x: get_col6(x['col3'], x['col4'], x['col5']),
axis=1)
df['col7'] = df.apply(lambda x: get_col7(x['col4'], x['col6']), axis=1)
Run Code Online (Sandbox Code Playgroud)
其中每个计算列都有单独的函数,每个函数都依赖于前面列的某种组合。
但是,由于计算列的值是相互依赖的,因此我认为使用如下所示的函数一次计算所有新列会更加高效和优雅:
def get_cols(col1, col2, col3):
#some calculations...
return {'col4': col4,
'col5': col5,
'col6': col6,
'col7': col7}
Run Code Online (Sandbox Code Playgroud)
有没有办法使用熊猫来做到这一点?
由于您想要保留以前的列,因此可以从新列中创建一个 Series,然后将该新 Series 对象附加到原始 Series。请记住,输入get_cols是原始 DataFrame 中的单独行(因此是一个 Series)。
import pandas as pd
import numpy as np
def get_cols(cols):
col4 = cols[0] * 2
col5 = cols[1] * 2
col6 = cols[2] * 2
return cols.append(pd.Series([col4, col5, col6], index=['col4', 'col5', 'col6']))
col1 = [np.random.randn()] * 10
col2 = [np.random.randn()] * 10
col3 = [np.random.randn()] * 10
df = pd.DataFrame({'col1': col1,
'col2': col2,
'col3': col3 })
df = df.apply(get_cols, axis=1)
print(df)
col1 col2 col3 col4 col5 col6
0 -0.809803 0.522547 0.064061 -1.619606 1.045093 0.128122
1 -0.809803 0.522547 0.064061 -1.619606 1.045093 0.128122
2 -0.809803 0.522547 0.064061 -1.619606 1.045093 0.128122
3 -0.809803 0.522547 0.064061 -1.619606 1.045093 0.128122
4 -0.809803 0.522547 0.064061 -1.619606 1.045093 0.128122
5 -0.809803 0.522547 0.064061 -1.619606 1.045093 0.128122
6 -0.809803 0.522547 0.064061 -1.619606 1.045093 0.128122
7 -0.809803 0.522547 0.064061 -1.619606 1.045093 0.128122
8 -0.809803 0.522547 0.064061 -1.619606 1.045093 0.128122
9 -0.809803 0.522547 0.064061 -1.619606 1.045093 0.128122
Run Code Online (Sandbox Code Playgroud)
这可能对您有帮助:pandas apply function that returns multiple value to rows in pandas dataframe
正确的方法是使用第二个函数“get_cols”返回列表而不是字典,然后使用 apply。