Mai*_*upo 5 python python-3.x pandas
假设我从一个包含一些数据和一列数量的数据框开始:
In: df=pd.DataFrame({'first-name':['Jan','Leilani'],'Qty':[2,4]})
Out: Qty first-name
2 Jan
4 Leilani
Run Code Online (Sandbox Code Playgroud)
我想创建一个数据框,将数据复制并标记到新行中,次数等于每行上的数量。输出应该如下所示:
Qty first-name position
2 Jan 1
2 Jan 2
4 Leilani 1
4 Leilani 2
4 Leilani 3
4 Leilani 4
Run Code Online (Sandbox Code Playgroud)
我可以像这样使用 python 来做到这一点:
l=[]
x=0
for idx in df.index:
x=0
for _ in range(df.loc[idx]['Qty']):
x+=1
tempSrs=df.loc[idx]
tempSrs['position']=x
l.append(tempSrs)
outDf=pd.DataFrame(l)
Run Code Online (Sandbox Code Playgroud)
这是非常缓慢的。有没有办法使用熊猫函数来做到这一点?这实际上是一个“unpivot”,在pandas 中是“melt”,但我无法弄清楚如何使用melt 函数来实现这一点。
谢谢,
随着repeat和cumcount
Newdf=df.reindex(df.index.repeat(df.Qty))
Newdf['position']=Newdf.groupby(level=0).cumcount()+1
Newdf
Out[931]:
Qty first-name position
0 2 jan 1
0 2 jan 2
1 4 jay 1
1 4 jay 2
1 4 jay 3
1 4 jay 4
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2432 次 |
| 最近记录: |