簡體   English   中英

Python Pandas:如何在groupby / transform操作中向數據框添加一個全新的列

[英]Python Pandas: how to add a totally new column to a data frame inside of a groupby/transform operation

我想在我的數據中標記一些分位數,並且對於DataFrame的每一行,我希望在名為“xtile”的新列中輸入以保存此值。

例如,假設我創建了一個這樣的數據框:

import pandas, numpy as np
dfrm = pandas.DataFrame({'A':np.random.rand(100), 
                         'B':(50+np.random.randn(100)), 
                         'C':np.random.randint(low=0, high=3, size=(100,))})

讓我們說我編寫自己的函數來計算數組中每個元素的五分位數。 我有自己的功能,但是例如只需要參考scipy.stats.mstats.mquantile。

import scipy.stats as st
def mark_quintiles(x, breakpoints):
    # Assume this is filled in, using st.mstats.mquantiles.
    # This returns an array the same shape as x, with an integer for which
    # breakpoint-bucket that entry of x falls into.

現在,真正的問題是如何使用transform為數據添加新列。 像這樣的東西:

def transformXtiles(dataFrame, inputColumnName, newColumnName, breaks):
    dataFrame[newColumnName] = mark_quintiles(dataFrame[inputColumnName].values, 
                                              breaks)
    return dataFrame

然后:

dfrm.groupby("C").transform(lambda x: transformXtiles(x, "A", "A_xtile", [0.2, 0.4, 0.6, 0.8, 1.0]))

問題是上面的代碼不會添加新列“A_xtile”。 它只是保持我的數據框不變。 如果我首先添加一個充滿虛擬值的列,例如NaN,稱為“A_xtile”,那么它成功覆蓋此列以包含正確的五分位標記。

但是,必須首先在列中寫入我可能想要添加的類似內容非常不方便。

請注意,簡單的apply在這里不起作用,因為它不知道如何理解每個組可能不同大小的結果數組。

apply遇到什么問題? 這適用於這個玩具示例,組長度不同:

In [82]: df
Out[82]: 
   X         Y
0  0 -0.631214
1  0  0.783142
2  0  0.526045
3  1 -1.750058
4  1  1.163868
5  1  1.625538
6  1  0.076105
7  2  0.183492
8  2  0.541400
9  2 -0.672809

In [83]: def func(x):
   ....:     x['NewCol'] = np.nan
   ....:     return x
   ....: 

In [84]: df.groupby('X').apply(func)
Out[84]: 
   X         Y  NewCol
0  0 -0.631214     NaN
1  0  0.783142     NaN
2  0  0.526045     NaN
3  1 -1.750058     NaN
4  1  1.163868     NaN
5  1  1.625538     NaN
6  1  0.076105     NaN
7  2  0.183492     NaN
8  2  0.541400     NaN
9  2 -0.672809     NaN

暫無
暫無

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

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