【问题标题】:split item to rows pandas将项目拆分为行熊猫
【发布时间】:2020-03-18 15:12:21
【问题描述】:

我有如下数据框中的数据。 我想将项目分成相同数量的行

>>> df
idx  a  
0  3  
1  5  
2  4 

从上面的数据框,我想要下面的

>>> df
idx  a  
0  1  
1  2  
2  3
3  1
4  2
5  3
6  4
7  5
8  1
9  2
10  3
11  4  

我尝试了几种方法,但都没有成功。

【问题讨论】:

    标签: python pandas numpy dataframe


    【解决方案1】:

    一种有趣的方式

    df.a.map(range).explode()+1 # may add reset_index(), however, I think keep the original index is good, and help us convert back.
    Out[158]: 
    idx
    0    1
    0    2
    0    3
    1    1
    1    2
    1    3
    1    4
    1    5
    2    1
    2    2
    2    3
    2    4
    Name: a, dtype: object
    

    【讨论】:

    • 您可能想要reset_index,因为 OP 需要唯一索引 @YOBEN_S
    • @VishnudevV 我会的
    【解决方案2】:

    这是series.repeat +Groupby. cumcount 的一种方式,假设idx 是索引——如果不是df.set_index('idx')['a']..rest of the code..

    (df['a'].repeat(df['a']).groupby(level=0).cumcount().add(1)
            .reset_index(drop=True).rename_axis('idx'))
    

    idx
    
    0     1
    1     2
    2     3
    3     1
    4     2
    5     3
    6     4
    7     5
    8     1
    9     2
    10    3
    11    4
    dtype: int64
    

    【讨论】:

      【解决方案3】:

      列表理解

      pd.DataFrame({'a': [x + 1 for y in df['a'] for x in range(y)]})
      
          a
      0   1
      1   2
      2   3
      3   1
      4   2
      5   3
      6   4
      7   5
      8   1
      9   2
      10  3
      11  4
      

      【讨论】:

        【解决方案4】:

        这是一个基于 numpy 的:

        a = (np.arange(df.a.max())+1)
        m = a <= df.a.values[:,None]
        df = pd.DataFrame(m.cumsum(1)[m], columns=['a'])
        

        print(df)
        
            a
        0   1
        1   2
        2   3
        3   1
        4   2
        5   3
        6   4
        7   5
        8   1
        9   2
        10  3
        11  4
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-08-30
          • 1970-01-01
          • 2020-12-26
          • 2021-12-04
          • 1970-01-01
          • 2016-12-03
          • 1970-01-01
          相关资源
          最近更新 更多