将行相乘并按单元格值追加到数据框 [英] Multiply rows and append to dataframe by cell value

查看:62
本文介绍了将行相乘并按单元格值追加到数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下数据框;

df = pd.DataFrame(
          {'X':('a','b','c','d'),
           'Y':('a','b','d','e'),
           'Z':('a','b','c','d'),
           '#':(1,2,1,3)
                })
df

我想在#"列中将数字大于1的行附加到该行中的数字减去1.df应该最好 然后看起来像这样;

I would like to append the rows with a figure higher than 1 in column '#' with the figure in that row minus 1. The df should preferably then look like this;

或者看起来像这样(行完全相乘);

Alternatively it may look like this (the rows multiplied completely);

顺便说一句,我已经广泛搜索了这个问题,但是找不到任何可以帮助我朝正确方向发展的东西.

Btw, I've searched this problem extensively, but cannot find anything that helps me in the right direction.

推荐答案

使用类似:

df = pd.DataFrame(np.repeat(df.values, df['#'], axis=0), columns=df.columns)
print (df)
   #  X  Y  Z
0  1  a  a  a
1  2  b  b  b
2  2  b  b  b
3  1  c  d  c
4  3  d  e  d
5  3  d  e  d
6  3  d  e  d

但是如果订单很重要:

dfs = []
for i in range(df['#'].max()):
    df = df[df['#'] > 0].copy()
    df['#'] -= 1
    dfs.append(df.iloc[:, 1:])

df1 = pd.concat(dfs, ignore_index=True) 
print (df1)
   X  Y  Z
0  a  a  a
1  b  b  b
2  c  d  c
3  d  e  d
4  b  b  b
5  d  e  d
6  d  e  d

这篇关于将行相乘并按单元格值追加到数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆