将同名行的最后一个条目应用于Pandas中所有同名行

2024-04-29 10:44:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个同名的数据集。例如,我希望数据(第0,1,2,3,4行)中的所有操作都与A的最后一行(第4行)的价格相同。所以所有的As都等于60。但是我想把它应用到我的全部数据中。B和C等的计算是一样的。我有很多数据。有可能在熊猫身上做到这一点吗?我不想将它们分组,所以我想保留所有数据集。下面是数据集的一个示例

   Brand      Price    Color      Category

0   A       10         Blue       Shoes
1   A       20         Red        Shoes
2   A       30         Yellow     Shoes 
3   A       40         Pink       Shoes 
4   A       60         Purple     Shoes  
5   B       100        Red        Shoes
6   B       130        Green      Shoes
7   B       150        Blue       Shoes
8   C       170        Yellow     Shoes
9   C       20         Green      Shoes

多谢各位


Tags: 数据示例as价格greenblueredprice
1条回答
网友
1楼 · 发布于 2024-04-29 10:44:44

使用由^{}创建的^{}by Serieskeep='last'作为每个组的最后一个值:

mapping = df.drop_duplicates('Brand', keep='last').set_index('Brand')['Price']
df['Price'] = df['Brand'].map(mapping)
print (df)
  Brand  Price   Color Category
0     A     60    Blue    Shoes
1     A     60     Red    Shoes
2     A     60  Yellow    Shoes
3     A     60    Pink    Shoes
4     A     60  Purple    Shoes
5     B    150     Red    Shoes
6     B    150   Green    Shoes
7     B    150    Blue    Shoes
8     C     20  Yellow    Shoes
9     C     20   Green    Shoes

如果需要通过多列定义组(例如BrandCategory),可以使用^{}^{}

df['Price'] = df.groupby(['Brand', 'Category'])['Price'].transform('last')
print (df)
  Brand  Price   Color Category
0     A     60    Blue    Shoes
1     A     60     Red    Shoes
2     A     60  Yellow    Shoes
3     A     60    Pink    Shoes
4     A     60  Purple    Shoes
5     B    150     Red    Shoes
6     B    150   Green    Shoes
7     B    150    Blue    Shoes
8     C     20  Yellow    Shoes
9     C     20   Green    Shoes

相关问题 更多 >