Python-将多个系列转换为字典

时间:2018-11-20 20:43:40

标签: python pandas

是否可以遍历系列列表并将其转换为词典?如果是这样,我还能为每本词典命名吗?

import pandas as pd

r = pd.Series([1,2,3,4])
s = pd.Series([5,6,7,8])
t = pd.Series([9,10,11,12])

series_list = [r,s,t]

#THIS PART OBVIOUSLY NOT CORRECT
for each in series_list: 
    each.to_dict()

1 个答案:

答案 0 :(得分:0)

让我们使用熊猫数据框!

首先让我们命名这些系列:

r.name = 'r'
s.name = 's'
t.name = 't'

或串联构造如下:

r = pd.Series([1,2,3,4],name='r')
s = pd.Series([5,6,7,8], name='s')
t = pd.Series([9,10,11,12], name='t')
series_list = [r,s,t]

df = pd.concat(series_list, axis=1)

然后使用to_dict

df.to_dict(orient='series')

输出:

{'r': 0    1
 1    2
 2    3
 3    4
 Name: r, dtype: int64, 's': 0    5
 1    6
 2    7
 3    8
 Name: s, dtype: int64, 't': 0     9
 1    10
 2    11
 3    12
 Name: t, dtype: int64}