对于以下数据框
df = pd.DataFrame({'Rounds':[1000,1000,1000,1000,3000,3000,4000,5000,6000,6000]})
我想要一个 for 循环,如果该值已经存在于前面的行中,则将一个固定的 int(在本例中为 25)添加到该值并创建:
df = pd.DataFrame({'Rounds':[1000,1025,1050,1075,3000,3025,4000,5000,6000,6025]})
一开始我试过
for i in df.index:
if df.iat[i,1] == df.iloc[i-1,1]:
df.iat[i,1] = df.iat[i-1,1]+25
问题是它不适用于一列中超过两个相似的值,我想给列名称“Rounds”而不是列的索引。
最佳答案
你需要groupby.cumcount
:
df['Rounds'] += df.groupby('Rounds').cumcount()*25
输出:
Rounds
0 1000
1 1025
2 1050
3 1075
4 3000
5 3025
6 4000
7 5000
8 6000
9 6025
中级:
df.groupby('Rounds').cumcount()
0 0
1 1
2 2
3 3
4 0
5 1
6 0
7 0
8 0
9 1
dtype: int64
关于python - Pandas 数据框 : For loop that adds a fixed integer if the value exists in previous rows,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73134568/