重复数据框的行 [英] repeating the rows of a data frame
本文介绍了重复数据框的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试重复数据框的行.这是我的原始数据:
I'm trying repeat the rows of a dataframe. Here's my original data:
pd.DataFrame([
{'col1': 1, 'col2': 11, 'col3': [1, 2] },
{'col1': 2, 'col2': 22, 'col3': [1, 2, 3] },
{'col1': 3, 'col2': 33, 'col3': [1] },
{'col1': 4, 'col2': 44, 'col3': [1, 2, 3, 4] },
])
这给了我
col1 col2 col3
0 1 11 [1, 2]
1 2 22 [1, 2, 3]
2 3 33 [1]
3 4 44 [1, 2, 3, 4]
我想根据col3中数组的长度重复行,即我想要一个像这样的数据框.
I'd like to repeat the rows depending on the length of the array in col3 i.e. I'd like to get a dataframe like this one.
col1 col2
0 1 11
1 1 11
2 2 22
3 2 22
4 2 22
5 3 33
6 4 44
7 4 44
8 4 44
9 4 44
完成此操作的好方法是什么?
What's a good way accomplishing this?
推荐答案
您还可以使用 index.repeat
You can also use reindex
and index.repeat
df = df.reindex(df.index.repeat(df.col3.apply(len)))
df = df.reset_index(drop=True).drop("col3", axis=1)
# To reset index and drop col3
# Output:
col1 col2
0 1 11
1 1 11
2 2 22
3 2 22
4 2 22
5 3 33
6 4 44
7 4 44
8 4 44
9 4 44
这篇关于重复数据框的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文