繁体   English   中英

重复数据帧的行

[英]repeating the rows of a data frame

我正在尝试重复数据帧的行。 这是我的原始数据:

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中数组的长度重复行,即我想获得像这样的数据帧。

   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

实现这一目标的好方法是什么?

您还可以使用reindexindex.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

您可以将列表理解与zip一起使用。

>>> pd.DataFrame([row for row, count in zip(df[['col1', 'col2']].values, df['col3']) 
                  for _ in range(len(count))], columns=df.columns[:2])
   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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM