Rot*_*ail 8 python dataframe pandas pandas-groupby
我有一个 Pandas 数据框,其中包含变量名称、每个变量的值和count(显示该行的频率):
df = pd.DataFrame({'var':['A', 'B', 'C'], 'value':[10, 20, 30], 'count':[1,2,3]})
var value count
A 10 1
B 20 2
C 30 3
Run Code Online (Sandbox Code Playgroud)
我想用来count获得这样的输出:
var value
A 10
B 20
B 20
C 30
C 30
C 30
Run Code Online (Sandbox Code Playgroud)
最好的方法是什么?
您可以使用index.repeat:
i = df.index.repeat(df['count'])
d = df.loc[i, :'value'].reset_index(drop=True)
Run Code Online (Sandbox Code Playgroud)
var value
0 A 10
1 B 20
2 B 20
3 C 30
4 C 30
5 C 30
Run Code Online (Sandbox Code Playgroud)