我想根据imageno + 1出现多少次在新的df(df2)中打印每一行。因此,在下面的数据中,第1行应打印两次(有两个7s),第2行应打印两次,第3行应打印两次,第4行应打印一次(有一个8),第5行应打印一次,等等。
import pandas as pd
print(df)
x-position y-position imageno
1 220 220 6
2 627 220 6
3 620 220 6
4 220 220 7
5 628 220 7
6 621 220 8
df2 = pd.DataFrame(columns=['x-position', 'y-position', 'imageno'])
答案 0 :(得分:3)
IIUC,使用Series.value_counts
创建一个助手系列,然后使用Series.map
,index.repeat
和DataFrame.loc
获得所需的数字或重复次数:
df = pd.DataFrame({'x-position': {1: 220, 2: 627, 3: 620, 4: 220, 5: 628, 6: 621}, 'y-position': {1: 220, 2: 220, 3: 220, 4: 220, 5: 220, 6: 220}, 'imageno': {1: 6, 2: 6, 3: 6, 4: 7, 5: 7, 6: 8}})
s = df['imageno'].value_counts()
df2 = df.loc[df.index.repeat(df['imageno'].add(1).map(s).fillna(0).astype(int))]
[出]
x-position y-position imageno
1 220 220 6
1 220 220 6
2 627 220 6
2 627 220 6
3 620 220 6
3 620 220 6
4 220 220 7
5 628 220 7
答案 1 :(得分:2)
IIUC merge
在调整'imageno'
df.assign(imageno=df.imageno+1).merge(df[['imageno']],on='imageno').assign(imageno=lambda x : x['imageno']-1)
Out[894]:
x-position y-position imageno
0 220 220 6
1 220 220 6
2 627 220 6
3 627 220 6
4 620 220 6
5 620 220 6
6 220 220 7
7 628 220 7