簡體   English   中英

如何遍歷數據框中的列並同時更新兩個新列?

[英]How to iterate through a column in dataframe and update two new columns simultaneously?

我知道我可以向數據幀添加一列,並將其值更新為函數返回的值,如下所示:

df=pd.DataFrame({'x':[1,2,3,4]})

def square(x):
    return x*x

df['x_squared'] = [square(i) for i in df['x']]

但是,我遇到的問題是實際函數返回兩個項目,我想將這兩個項目放在兩個不同的新列中。 我在這里寫了一個偽代碼來更清楚地描述我的問題:

df=pd.DataFrame({'x':[1,2,3,4]})

def squareAndCube(x):
    return x*x, x*x*x

#below is a pseudo-code
df['x_squared'], df['x_cubed'] = [squareAndCube(i) for i in df['x']]

上面的代碼給我一個錯誤消息,說“打開太多的值”。 那么,我該如何解決這個問題呢?

你可以用矢量化的方式做,就像這樣 -

df['x_squared'], df['x_cubed'] = df.x**2,df.x**3

或者使用那個自定義函數,就像這樣 -

df['x_squared'], df['x_cubed'] = squareAndCube(df.x)

回到你的循環案例,在作業的右側,你有:

In [101]: [squareAndCube(i) for i in df['x']]
Out[101]: [(1, 1), (4, 8), (9, 27), (16, 64)]

現在,在左側,你有df['x_squared'], df['x_cubed'] = 因此,它期望所有行的平方數作為第一個輸入賦值。 從上面顯示的列表中,第一個元素不是,它實際上是第一行的正方形和立方體。 因此,修復是“轉置”該列表並指定為新列。 因此,修復將是 -

In [102]: L = [squareAndCube(i) for i in df['x']]

In [103]: map(list, zip(*L))  # Transposed list
Out[103]: [[1, 4, 9, 16], [1, 8, 27, 64]]

In [104]: df['x_squared'], df['x_cubed'] = map(list, zip(*L))

對於NumPy broadcasting的熱愛!

df['x_squared'], df['x_cubed'] = (df.x.values[:,None]**[2,3]).T

這適用於正數。 思考如何概括,但這種解決方案的簡潔讓我心煩意亂。

df = pd.DataFrame(range(1, 10))
a = np.arange(1, 4).reshape(1, -1)

np.exp(np.log(df).dot(a))

在此輸入圖像描述

如何像這樣使用df.loc

df=pd.DataFrame({'x':[1,2,3,4]})

def square(x):
    return x*x

df['x_squared'] = df['x_cubed'] = None
df.loc[:, ['x_squared', 'x_cubed']] = [squareAndCube(i) for i in df['x']]

   x  x_squared  x_cubed
0  1          1        1
1  2          4        8
2  3          9       27
3  4         16       64

非常接近你所擁有的,但df.loc需要存在列才能工作。

對於不熟悉的人來說,df.loc有兩個參數,一個你想要處理的行列表 - 在這種情況下:這意味着所有這些參數,以及一個列列表 - ['x_squared', 'x_cubed']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM