python-3.x - 根据对应的列值重复列,根据熊猫数据框中的总值重复行
问题描述
我有以下数据框:
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)
解决方案
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
推荐阅读
- react-native - 从 react-redux 中的父组件更新子组件的状态
- google-chrome - 有错误的页面速度:灯塔返回错误:没有 FCP
- python - 双击打开项目时不显示 Python 输入
- python - python中字符串内的按位运算
- laravel - Laravel 守卫、大门和政策
- rascal - Rascal 可以在方法中返回操作系统吗?
- mysql - MySQL(MariaDB)按索引交换列位置,不使用 after
- angular - 尝试更新 ngrx 存储时发生错误
- powerbi - 嵌入 PowerBI 时是否可以将筛选器应用于仪表板或磁贴?
- php - php 文件中不允许 chmod 操作