首页 > 解决方案 > 根据对应的列值重复列,根据熊猫数据框中的总值重复行

问题描述

我有以下数据框:

df1_given =pd.DataFrame.from_dict({'col_0':[0, 3], 'col_1':[0.1, 2], 'col_2':[0.2, 0], 'col_3':[0.3, 2]})

所需的数据帧如下:

df2_result =pd. DataFrame.from_dict({'col_0_0':[0, 0, 0, 0, 0, 0], 'col_0_1':[0, 0, 0, 0, 0, 0],'col_0_2':[0, 0, 0, 0, 0, 0],
   'col_1_0':[0.1, 0.1, 0.1, 0.1, 0.1, 0.1],'col_1_1':[0.1, 0.1, 0.1, 0.1, 0.1, 0.1],
   'col_3_0':[0.3, 0.3, 0.3, 0.3, 0.3, 0.3], 'col_3_1':[0.3, 0.3, 0.3, 0.3, 0.3, 0.3]})

我尝试使用 .repeat() 函数,但它不起作用。问题是基于相应的列值(即,df_given 中的 row2)和基于 row2 中的总值的行来传播/重复列。请注意,我在实际数据框中的 df_given 的 row2 中有大量的列和较大的值。

df_tried = pd.DataFrame(df1_given.values.repeat(df1_given.col_0, axis=0), columns = df1_given.columns)

标签: python-3.xpandas

解决方案


import pandas as pd

df =pd.DataFrame.from_dict({'col_0':[0, 3], 'col_1':[0.1, 2], 'col_2':[0.2, 0], 'col_3':[0.3, 2]})


from collections import defaultdict
my_dict = defaultdict(list)

cols = list(df.columns)

for i in  range (0,len(cols)):
    if (df.iloc[1,i])>0:
        for x in range(0,int(df.iloc[1,i])):
            y = str(cols[i])
            my_dict[y+'_'+str(x)].append( df.iloc[0,i])

df_2 = pd.DataFrame(my_dict)
print(df_2)

但我不明白你在结果中等待 6 行而不是 1 行背后的逻辑。但我认为这解决了你的问题。

df_2
Out[57]: 
   col_0_0  col_0_1  col_0_2  col_1_0  col_1_1  col_3_0  col_3_1
0        0        0        0      0.1      0.1      0.3      0.3

推荐阅读