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

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

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?

hitpick_df['count'] = 0

# Iterate over the rows and increment the count
i = 1
for i in range(1, len(hitpick_df)):
  if hitpick_df['Destination'][i] == hitpick_df['Destination'][i - 1]:
    hitpick_df.loc[i, 'count'] = hitpick_df.loc[i - 1, 'count'] + 1
  else:
    hitpick_df.loc[i, 'count'] = 1

# Print the DataFrame
print(hitpick_df)

What resulted was a column full of 1's

答案1

得分: 1

尝试使用 cumcount

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

输出:

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

Try cumcount

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

output:

   well_id  plate_number
0       A2      1
1       A3      1
2       A4      1
3       B2      1
4       B3      1
5       B4      1
6       A2      2
7       A3      2
8       A4      2
9       B2      2
10      B3      2
11      B4      2
12      A2      3
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:

确定