2017-10-18 214 views
1

我知道如何在数据框上使用apply函数来计算新列并将它们附加到数据框。我的问题是,如果我有一个函数,它将几个值(对应于当前在数据框中的列)作为参数并返回一个字典(对应于我想添加到数据框的列),是否有简单/优雅的方式将此函数应用于数据框并生成新列?Python/pandas - 使用DataFrame.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) 

,我为每个计算列单独的功能,其中的每一个依赖于以前的专栏的某种组合。

不过,由于计算列的值是互相依赖的,我认为这将是更有效和优雅的使用功能,像下面这样一次全部计算新列:

def get_cols(col1, col2, col3): 
    #some calculations... 
    return {'col4': col4, 
      'col5': col5, 
      'col6': col6, 
      'col7': col7} 

有没有办法使用熊猫来做到这一点?

+0

你能给这个例子输入和输出吗?即使只是一个有代表性的专栏,可能您并不需要您尝试创建的所有专栏(?)。这看起来可能是一个不必要的缓慢运行的方式来解决你的问题。 – roganjosh

回答

0

由于您希望保留以前的列,您可以在新列中创建一个系列,然后将该新系列对象附加到原始系列。请记住,get_cols的输入是来自原始DataFrame的个人(因此是系列)。

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