我有以下数据集
Item Count
A 60
A 20
A 21
B 33
B 33
B 32
要复制的代码:
import pandas as pd
df = pd.DataFrame([
['A', 60],
['A', 20],
['A', 21],
['B', 33],
['B', 33],
['B', 32],
],
columns=['Item', 'Count'])
假设我只需通过添加1来更改每组“项目”列的最大值。
输出应如下所示:
Item Count New_Count
A 60 61
A 20 20
A 21 21
B 33 34
B 33 34
B 32 32
我尝试了df['New_Count']=df.groupby(['Item'])['Count'].transform(lambda x: max(x)+1)
,但是“ Count”中的所有值都被每个组+1的最大值代替。
Item Count New_Count
A 60 61
A 20 61
A 21 61
B 33 34
B 33 34
B 32 34
答案 0 :(得分:12)
使用idxmax
:
idx = df.groupby("Item")["Count"].idxmax()
df["New_Count"] = df["Count"]
df.loc[idx, "New_Count"] += 1
这只会增加每个组中第一次出现的第一个最大值。
如果要在平局的情况下增加所有最大值,可以改用transform
。只需将上面的第一行替换为:
idx = df.groupby("Item")["Count"].transform(max) == df["Count"]
答案 1 :(得分:5)
您可以使用idxmax()
来获取每个组的最大值的IDx,并仅递增这些项目,例如:
max_idxs = df.groupby(['Item'])['Count'].idxmax()
df['New_Count']=df['Count'] # copy entire column
df['New_Count'][max_idxs]+=1 # increment only the maximum item for each group by 1
答案 2 :(得分:5)
这是不使用groupby而是使用TSlicerElement
duplicated
输出:
df.loc[~df.sort_values('Count', ascending=False).duplicated('Item'), 'Count'] += 1
答案 3 :(得分:1)
要更改所有重复的最大值中的值,您将需要.groupby()
,.join()
和np.where()
df = pd.DataFrame([
['A', 60],
['A', 60],
['A', 20],
['A', 21],
['B', 21],
['B', 33],
['B', 34],
], columns=['Item', 'Count'])
s = df.groupby('Item')['Count'].max().rename('newCount')
df = df.set_index('Item').join(s).reset_index()
df['newCount'] = np.where(df['Count'] != df['newCount'], df['Count'], (df['newCount'] + 1))
df.head(10)
#output
Item Count newCount
0 A 60 61
1 A 60 61
2 A 20 20
3 A 21 21
4 B 21 21
5 B 33 33
6 B 34 35
我们可以按照@Dan的建议,将.join()
替换为.transform()
df['newCount'] = df.groupby('Item')['Count'].transform('max')
df['newCount'] = np.where(df['Count'] != df['newCount'], df['Count'], (df['newCount'] + 1))
#output
Item Count newCount
0 A 60 61
1 A 60 61
2 A 20 20
3 A 21 21
4 B 21 21
5 B 33 33
6 B 34 35