如何计算列表重复的次数并将其添加到pandas数据框中的列。

huangapple go评论94阅读模式
英文:

How to count the number times a list repeats and adding to column in pandas dataframe

问题

我有一个包含两列'Plate Number'和'Well ID'的数据帧。

plate_number well_id
1 A2
1 A3
1 A4
1 B2
1 B3
1 B4
1 A2
1 A3
1 A4
1 B2
1 B3
1 B4
1 A2
1 A3

well_id列是使用重复列表[A2, A3, A4, B2, B3, B4]填充的,现在我需要找到一种方法,每次该列表重复时通过加1来更改盘号,以产生以下数据帧。

plate_number well_id
1 A2
1 A3
1 A4
1 B2
1 B3
1 B4
2 A2
2 A3
2 A4
2 B2
2 B3
2 B4
3 A2
3 A3

我有点不知所措,有关如何在Python中继续进行的任何建议吗?

英文:

I have a dataframe with two columns 'Plate Number' and 'Well ID'.

plate_number well_id
1 A2
1 A3
1 A4
1 B2
1 B3
1 B4
1 A2
1 A3
1 A4
1 B2
1 B3
1 B4
1 A2
1 A3

The well_id column was populated using a repeated list = [A2, A3, A4, B2, B3, B4] now I need to find a way to to change the plate number everytime this list repeats by adding 1 so it produces the following dataframe.

plate_number well_id
1 A2
1 A3
1 A4
1 B2
1 B3
1 B4
2 A2
2 A3
2 A4
2 B2
2 B3
2 B4
3 A2
3 A3

I am kind of at a loss on how to do it, any advice on how to move forward with this in python?

  1. hitpick_df['count'] = 0
  2. # Iterate over the rows and increment the count
  3. i = 1
  4. for i in range(1, len(hitpick_df)):
  5. if hitpick_df['Destination'][i] == hitpick_df['Destination'][i - 1]:
  6. hitpick_df.loc[i, 'count'] = hitpick_df.loc[i - 1, 'count'] + 1
  7. else:
  8. hitpick_df.loc[i, 'count'] = 1
  9. # Print the DataFrame
  10. print(hitpick_df)

What resulted was a column full of 1's

答案1

得分: 1

尝试使用 cumcount

  1. df['plate_number'] = df.groupby('well_id').cumcount() + 1

输出:

  1. well_id plate_number
  2. 0 A2 1
  3. 1 A3 1
  4. 2 A4 1
  5. 3 B2 1
  6. 4 B3 1
  7. 5 B4 1
  8. 6 A2 2
  9. 7 A3 2
  10. 8 A4 2
  11. 9 B2 2
  12. 10 B3 2
  13. 11 B4 2
  14. 12 A2 3
  15. 13 A3 3
英文:

Try cumcount

  1. df['plate_number'] = df.groupby('well_id').cumcount() + 1

output:

  1. well_id plate_number
  2. 0 A2 1
  3. 1 A3 1
  4. 2 A4 1
  5. 3 B2 1
  6. 4 B3 1
  7. 5 B4 1
  8. 6 A2 2
  9. 7 A3 2
  10. 8 A4 2
  11. 9 B2 2
  12. 10 B3 2
  13. 11 B4 2
  14. 12 A2 3
  15. 13 A3 3

huangapple
  • 本文由 发表于 2023年5月18日 10:05:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76277282.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定