[英]Pandas dataframe get first row of each group and copy to other rows
我有一個如下所示的 Pandas DataFrame。
df = pd.DataFrame({'id' : [1,1,1,2,2,3,3,3,3,4,4,5,6,6,6,7,7],
'value' : ["first","second","second","first",
"second","first","third","fourth",
"fifth","second","fifth","first",
"first","second","third","fourth","fifth"]})
我想通過 ["id","value"] 對其進行分組,獲取每個組的第一行,並使用其值覆蓋該組剩余行中的值(因此結果表的維度相同作為源表)
id value
0 1 first
1 1 second
2 1 second
3 2 second
4 2 first
5 3 first
6 3 third
7 3 fourth
8 3 fifth
9 4 second
10 4 fifth
11 5 first
12 6 first
13 6 second
14 6 third
15 7 fourth
16 7 fifth
預期結果
id value
0 1 first
1 1 first
2 1 first
3 2 second
4 2 second
5 3 first
6 3 first
7 3 first
8 3 first
9 4 second
10 4 second
11 5 first
12 6 first
13 6 first
14 6 first
15 7 fourth
16 7 fourth
我嘗試了很多方法,但無濟於事......有什么想法嗎?
將GroupBy.transform
與GroupBy.first
GroupBy.transform
使用:
df['value'] = df.groupby('id')['value'].transform('first')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.