英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论