2017-10-18 213 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