在 pandas 中将行拆分为多行

编程入门 行业动态 更新时间:2024-10-26 12:34:10
本文介绍了在 pandas 中将行拆分为多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个DataFrame,其格式如下(简化)

I have a DataFrame with a format like this (simplified)

a b 43 a c 22

我希望通过以下方式对此进行分解.

I would like this to be split up in the following way.

a b 20 a b 20 a b 1 a b 1 a b 1 a c 20 a c 1 a c 1

在这里,行数除以20,然后剩下的行数也一样.我有一个解决方案,基本上可以对行进行迭代并填充字典,然后可以将其转换回Dataframe,但我想知道是否有更好的解决方案.

Where I have as many rows as the number divides by 20, and then as many rows as the remainder. I have a solution that basically iterates over the rows and fills up a dictionary which can then be converted back to Dataframe but I was wondering if there is a better solution.

推荐答案

您可以先对模数使用地板分位数,然后通过constructor与DataFrame. org/doc/numpy/reference/generated/numpy.repeat.html"rel =" nofollow noreferrer> numpy.repeat .

You can use floor divison with modulo first and then create new DataFrame by constructor with numpy.repeat.

最近需要 numpy.concatenate ,其中list comprehension表示C:

a,b = df.C // 20, df.C % 20 #print (a, b) cols = ['A','B'] df = pd.DataFrame({x: np.repeat(df[x], a + b) for x in cols}) df['C'] = np.concatenate([[20] * x + [1] * y for x,y in zip(a,b)]) print (df) A B C 0 a b 20 0 a b 20 0 a b 1 0 a b 1 0 a b 1 1 a c 20 1 a c 1 1 a c 1

更多推荐

在 pandas 中将行拆分为多行

本文发布于:2023-07-09 14:58:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1087142.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中将   pandas

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!