2017-06-02 33 views
0

考慮下面的例子, - 給出數據幀具有列X - 計算X^2,X^3,......並追加到原始數據幀什麼對象被熊貓中的lambda函數提取?

# platform info. 
import sys 
print sys.version 

# this example is to show how to calculate features of x, x^2, x^3... 
import pandas as pd 
df = pd.DataFrame([2], columns=['x']) 
print df 

for i in range(4): 
    # trying to extract first and last column, then multiply them and append to the right 
    # method 1 works 
    df2 = df.iloc[:,[0,-1]].apply(lambda (x,y):x*y, axis=1) 
    print df2.shape 
    df = pd.concat([df, df2], axis=1) 
print df.head(1) 

df = pd.DataFrame([2], columns=['x']) 
for i in range(4): 
    # trying to extract first and last column, then multiply them and append to the right 
    # method 2 doesn't work as expected. Why? 
    df2 = df.apply(lambda x:x[0]*x[-1], axis=1) 
    print df2.shape 
    df = pd.concat([df, df2], axis=1) 
print df.head(1) 

你能告訴我之間的區別這兩種方法?對於第二個示例,通過使用lambda函數對df抽取哪個對象?我期待行矢量,但它不是。

謝謝!

下面是我的運行結果:

2.7.10 (default, Feb 7 2017, 00:08:15) 
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] 
    x 
0 2 
(1,) 
(1,) 
(1,) 
(1,) 
    x 0 0 0 0 
0 2 4 8 16 32 
(1,) 
(1,) 
(1, 2) 
(1, 4) 
    x 0 0 0 0  0  0  0  0 
0 2 4 16 64 256 1024 4096 16384 65536 
+0

你試過把它從一個lambda成一個函數,然後打印出來? –

+0

我不知道你的意思。你指的是什麼部分你能否詳細說明一下?這裏有一點歷史......我第一次嘗試方法2,它不起作用。然後嘗試方法1,它的工作。我想知道爲什麼方法2不能按預期工作。 – FrankZhu

+0

*沒有按預期工作*是什麼意思?它怎麼不等等......? –

回答

0

我覺得你的「意外」的行爲從差值進來X [0]和X你拉姆達功能[-1]。雖然x [-1]返回Series的一個片段(最後一個值),但x [0]將返回索引爲0的所有行(這意味着您的案例中的所有行,因爲它們從數據幀獲得索引)。 您可以通過使用ILOC用於查找解決此問題:

df = pd.DataFrame([2], columns=['x']) 
for i in range(4): 
    df2 = df.apply(lambda x:x.iloc[0]*x.iloc[-1], axis=1) 
    print df2.shape 
    df = pd.concat([df, df2], axis=1) 
print df.head(1) 
+0

非常感謝! lambda函數仍然返回一個行向量,但是x [0]不是第一個元素,它返回列名稱的計算結果爲0的所有列(不是我認爲的行)。由於我沒有爲df2指定列名,所有附加的列名是0.因此,x [0]將返回[4],[4,16],[4,16,64,256],並且您修復了工作。 – FrankZhu