repeating the rows of a data frame

元气小坏坏 提交于 2019-11-28 04:20:24

问题


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] },
    ])

which gives me

   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]

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?


回答1:


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



回答2:


You can use a list comprehension together with 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


来源:https://stackoverflow.com/questions/52352226/repeating-the-rows-of-a-data-frame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!