[英]How to replicate rows based on value of a column in same pandas dataframe
[英]Python: How to replicate rows in Dataframe with column value but changing the column value to its range
有一個 dataframe df
Store Aisle Table
11 59 2
11 61 3
需要復制這些行 w.r.t。 更改“表”列值時的“表”列次數如下:
Store Aisle Table
11 59 1
11 59 2
11 61 1
11 61 2
11 61 3
嘗試了下面的代碼,但這不會改變值,而是復制同一行 n 次。
df.loc[df.index.repeat(df['Table'])]
謝謝!
之后您可以執行groupby().cumcount()
:
out = df.loc[df.index.repeat(df['Table'])]
out['Table'] = out.groupby(level=0).cumcount() + 1
Output:
Store Aisle Table
0 11 59 1
0 11 59 2
1 11 61 1
1 11 61 2
1 11 61 3
我們可以嘗試explode
out = df.assign(Table=df['Table'].map(range)).explode('Table')
Out[160]:
Store Aisle Table
0 11 59 0
0 11 59 1
1 11 61 0
1 11 61 1
1 11 61 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.