将元组列表转换为Pandas系列

Zak*_*akS 5 python dictionary tuples series pandas

我有一个元组列表,我想转换为系列.

return array2

[(0, 0.07142857142857142),
  (0, 0.07142857142857142),
  (1, 0.08333333333333333),
  (1, 0.3333333333333333),
  (1, 0.3333333333333333),
  (1, 0.08333333333333333),
  (3, 0.058823529411764705),
  (3, 0.058823529411764705)]
Run Code Online (Sandbox Code Playgroud)

我尝试通过将列表转换为字典然后转换为系列来完成此操作:

 a = pd.Series(dict(array2))
Run Code Online (Sandbox Code Playgroud)

然而,最终的系列并不像我需要的那样表现.它似乎掉落key:value(可能是任意的?)

例如

return a

 0    0.071429
 1    0.083333
 3    0.058824
Run Code Online (Sandbox Code Playgroud)

如何在不丢弃任何键值对的情况下获得系列?

jez*_*ael 7

DataFrame构造函数与set_index第一列一起使用,然后选择第二列用于Series

a = pd.DataFrame(array2).set_index(0)[1]
print (a)
0
0    0.071429
0    0.071429
1    0.083333
1    0.333333
1    0.333333
1    0.083333
3    0.058824
3    0.058824
Name: 1, dtype: float64
Run Code Online (Sandbox Code Playgroud)

或者创建 2 个列表并传递给Series构造函数:

idx = [x[0] for x in array2]
vals = [x[1] for x in array2]

a = pd.Series(vals, index=idx)
print (a)
0    0.071429
0    0.071429
1    0.083333
1    0.333333
1    0.333333
1    0.083333
3    0.058824
3    0.058824
dtype: float64
Run Code Online (Sandbox Code Playgroud)


jpp*_*jpp 5

使用zip和顺序解包:

idx, values = zip(*L)

a = pd.Series(values, idx)
Run Code Online (Sandbox Code Playgroud)

使用重复索引(如您的数据)dict将无济于事,因为不允许使用重复的字典键:dict仅对提供的​​每个键取最后一个值。