![](/img/trans.png)
[英]Python pandas equivalent to R's group_by, mutate, and ifelse
[英]equivalent python and pandas operation for group_by + mutate + indexing column vectors within mutate in R
Python 中的示例數據框:
d = {'col1': ["a", "a", "a", "b", "b", "b", "c", "c", "c"],
'col2': [3, 4, 5, 1, 3, 9, 5, 7, 23]}
df = pd.DataFrame(data=d)
現在,我想使用 Pandas 在 Python 中獲得與使用下面的代碼在 R 中獲得的輸出相同的輸出。 所以我想在 col2 中按組獲得 col1 中百分比的變化。
data.frame(col1 = c("a", "a", "a", "b", "b", "b", "c", "c", "c"),
col2 = c(3, 4, 5, 1, 3, 9, 16, 18, 23)) -> df
df %>%
dplyr::group_by(col1) %>%
dplyr::mutate(perc = (dplyr::last(col2) - col2[1]) / col2[1])
在python中,我試過:
def perc_change(column):
index_1 = tu_in[column].iloc[0]
index_2 = tu_in[column].iloc[-1]
perc_change = (index_2 - index_1) / index_1
return(perc_change)
d = {'col1': ["a", "a", "a", "b", "b", "b", "c", "c", "c"],
'col2': [3, 4, 5, 1, 3, 9, 5, 7, 23]}
df = pd.DataFrame(data=d)
df.assign(perc_change = lambda x: x.groupby["col1"]["col2"].transform(perc_change))
但它給了我一個錯誤說:“方法”對象不可下標。
我是 python 的新手,並試圖將一些 R 代碼轉換為 python。 我怎樣才能以優雅的方式解決這個問題? 謝謝!
你不想在這里transform
。 當您的聚合返回每個組的標量值並且您希望將該結果廣播到原始 DataFrame 中屬於該組的所有行時,通常會使用transform
。 因為GroupBy.pct_change
已經返回一個像原始索引一樣的結果,所以你聚合並分配回來。
df['perc_change'] = df.groupby('col1')['col2'].pct_change()
# col1 col2 perc_change
#0 a 3 NaN
#1 a 4 0.333333
#2 a 5 0.250000
#3 b 1 NaN
#4 b 3 2.000000
#5 b 9 2.000000
#6 c 5 NaN
#7 c 7 0.400000
#8 c 23 2.285714
但是,如果您需要的是組內的總體百分比變化,即第一個和最后一個值的差異除以第一個值,那么您將需要轉換。
df.groupby('col1')['col2'].transform(lambda x: (x.iloc[-1] - x.iloc[0])/x.iloc[0])
0 0.666667
1 0.666667
2 0.666667
3 8.000000
4 8.000000
5 8.000000
6 3.600000
7 3.600000
8 3.600000
Name: col2, dtype: float64
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.