考慮下面的例子, - 給出數據幀具有列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
你試過把它從一個lambda成一個函數,然後打印出來? –
我不知道你的意思。你指的是什麼部分你能否詳細說明一下?這裏有一點歷史......我第一次嘗試方法2,它不起作用。然後嘗試方法1,它的工作。我想知道爲什麼方法2不能按預期工作。 – FrankZhu
*沒有按預期工作*是什麼意思?它怎麼不等等......? –