将元组列表转换为Pandas系列

14
我有一个元组列表,我想把它转换为Series。

我有一个元组列表,我想将其转换为Series。

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)]

我尝试通过将列表转换为字典,再转换为序列来实现此目的:

 a = pd.Series(dict(array2))

然而,生成的Series并不像我需要的那样运作。它似乎会删除key:value对(可能是任意的?)。

例如:

return a

 0    0.071429
 1    0.083333
 3    0.058824

如何获取一个序列而不丢失任何键值对?

6个回答

25

使用zip和序列解包:

idx, values = zip(*L)

a = pd.Series(values, idx)

在您的数据中存在重复索引,因此像 dict 这样的字典无法帮助您,因为不允许重复的字典键:对于提供的每个键,dict 只会保留最后一个值。


你能详细说明为什么需要使用吗?看起来是必需的。@jpp - Chris Kouts

8
使用 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

或者创建两个列表并传递给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

嗨,如果我只想要这些元组的一列... 怎么做呢 @jezrael - Nirali Khoda

4
你可以使用np.transpose解压缩列,然后创建一个pd.Series:
import numpy as np
import pandas as pd

x, y = np.transpose(array2)
pd.Series(y, x)

这比 pd.Series.T(转置)更快吗? - Wes Turner
2
或者,您可以使用 x,y = zip(* array2) 来避免加载Numpy。 这还保留了索引类型(int)。 - Bill
2
哦,@jpp已经提出了这个建议。抱歉。 - Bill

4

问题在于,当你将一个元组列表转换为字典时,Python会删除所有重复的键,并且只使用每个键的最后一个值。这是必要的,因为每个键在字典中只能出现一次。因此,您需要使用一种保留所有记录的方法。以下代码可以实现:

df = pd.DataFrame.from_records(array2, columns=['key', 'val'])
df = df.set_index('key')
a = df['val']

例子:

import pandas as pd
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)
]

df = pd.DataFrame.from_records(array2, columns=['key', 'val'])
df = df.set_index('key')
a = df['val']
print(a)
# key
# 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: val, dtype: float64

1
使用MultiIndex
pd.MultiIndex.from_tuples(L).to_frame()[1].reset_index(level=1,drop=True)
Out[79]: 
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

2
开箱即用的解决方案 :) - jezrael

0
假设你的元组列表是:
tuples = [(0, 0.07142857142857142),
  (0, 0.07142857142857142),
  (1, 0.08333333333333333),
  (1, 0.3333333333333333),
  (1, 0.3333333333333333),
  (1, 0.08333333333333333),
  (3, 0.058823529411764705),
  (3, 0.058823529411764705)]

我会使用(显式优于隐式):
pd.Series([value for _, value in tuples], index=[index for index, _ in tuples])

然而,我也会重新考虑系列数据格式是否合适和有意义:索引实际上应该像字典一样,即将唯一值映射到一个值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接