[英]Expand DataFrame column into multiple rows based on a count column in Python
This for loop should suffice:这个 for 循环应该足够了:
import pandas as pd
d = pd.DataFrame({"name" : ["John", "Eric"],
"days" : [1,3]})
for i, num in enumerate(d['days'].values):
for j in range(num-1):
d = d.append(d.iloc[i], ignore_index=True)
d = d.sort_values('name', ascending=False)
Output: d Output: d
name days
0 John 1
1 Eric 3
2 Eric 3
3 Eric 3
Explanation:解释:
num
in the column name also get the each of current row using enumerate
functionnum
还使用enumerate
function 获取当前行中的每一行Dataframe
' num-1 ' times, ignore_index
argument is set to False
so that the index is not duplicated Dataframe
' num-1 ' 次, ignore_index
参数设置为False
以便索引不重复.sort_values(<column name>)
to in the desired.sort_values(<column name>)
在所需的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.