将字典中的数据转换为行中具有索引的数据框
Converting data in the dictionary into a dataframe with index in the rows
我有以下问题。给定字典
dict = { 'value_1': [12,25,30,45,60] , 'value_2': [ 15,21,31]}
将上述字典转换为数据框的更简单方法是什么,其中一列是两个键的项目的串联,另一列是这些项目中每一个的索引?
以下应该是输出
index 0 1
0 value_11 12
1 value_12 25
2 value_13 30
3 value_14 45
4 value_15 60
0 value_21 15
1 value_22 21
2 value_23 31
我采用的方法非常耗时。
我首先拿走了这些物品并列出了清单。对于索引 I 运行 一个 for 循环 for i ,索引将是 'value_1'+str(i)
然后将所有内容组合到一个数据框中。有没有更简单的方法来做到这一点?
IIUC 我们使用 Series
解压你的 dict
,然后使用 cumcount
添加新列
s=pd.Series(d).apply(pd.Series).stack().reset_index(level=0)
s['level_0']=s['level_0']+s.groupby('level_0').cumcount().add(1).astype(str)
s
level_0 0
0 value_11 12.0
1 value_12 25.0
2 value_13 30.0
3 value_14 45.0
4 value_15 60.0
0 value_21 15.0
1 value_22 21.0
2 value_23 31.0
可能不是最快的,但你可以试试:
pd.concat(pd.DataFrame([[f'{k}{i+1}', val] for i,val in enumerate(v)])
for k,v in d.items() )
输出:
0 1
0 value_11 12
1 value_12 25
2 value_13 30
3 value_14 45
4 value_15 60
0 value_21 15
1 value_22 21
2 value_23 31
我有以下问题。给定字典
dict = { 'value_1': [12,25,30,45,60] , 'value_2': [ 15,21,31]}
将上述字典转换为数据框的更简单方法是什么,其中一列是两个键的项目的串联,另一列是这些项目中每一个的索引?
以下应该是输出
index 0 1
0 value_11 12
1 value_12 25
2 value_13 30
3 value_14 45
4 value_15 60
0 value_21 15
1 value_22 21
2 value_23 31
我采用的方法非常耗时。
我首先拿走了这些物品并列出了清单。对于索引 I 运行 一个 for 循环 for i ,索引将是 'value_1'+str(i)
然后将所有内容组合到一个数据框中。有没有更简单的方法来做到这一点?
IIUC 我们使用 Series
解压你的 dict
,然后使用 cumcount
s=pd.Series(d).apply(pd.Series).stack().reset_index(level=0)
s['level_0']=s['level_0']+s.groupby('level_0').cumcount().add(1).astype(str)
s
level_0 0
0 value_11 12.0
1 value_12 25.0
2 value_13 30.0
3 value_14 45.0
4 value_15 60.0
0 value_21 15.0
1 value_22 21.0
2 value_23 31.0
可能不是最快的,但你可以试试:
pd.concat(pd.DataFrame([[f'{k}{i+1}', val] for i,val in enumerate(v)])
for k,v in d.items() )
输出:
0 1
0 value_11 12
1 value_12 25
2 value_13 30
3 value_14 45
4 value_15 60
0 value_21 15
1 value_22 21
2 value_23 31