gpt4 book ai didi

python - pandas dataframe groupby 并填充第一行值

转载 作者:行者123 更新时间:2023-12-05 01:35:17 28 4
gpt4 key购买 nike

我有一个这样的df,

df = pd.DataFrame({
"Name" : ["A","B","C","D","E","F","G"],
"part number" : ["1","3","2","1","5","1","2"],
"detail1" : ["A","C","B","B","E","E","E"],
"detail2" : ["one","three","two","two","five","five","five"]
})


df
Name part number detail1 detail2
A 1 A one
B 3 C three
C 2 B two
D 1 B two
E 5 E five
F 1 E five
G 2 E five

我想按零件编号分组并用第一行值填充 detail1 和 detail2。

我的预期输出,

Name    part number detail1 detail2
A 1 A one
B 3 C three
C 2 B two
D 1 A one
E 5 E five
F 1 A one
G 2 B two

我试过了,df.groupby("part number")[["detail1","detail2"]].first() 但没有给出预期的输出,请帮忙。

最佳答案

部件号上使用groupby,并使用first转换列detail1detail2 > 并将此转换后的列分配回 df:

cols = ['detail1', 'detail2']
df[cols] = df.groupby('part number')[cols].transform('first')

结果:

print(df)
Name part number detail1 detail2
0 A 1 A one
1 B 3 C three
2 C 2 B two
3 D 1 A one
4 E 5 E five
5 F 1 A one
6 G 2 B two

关于python - pandas dataframe groupby 并填充第一行值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63067343/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com