Python 如何将熊猫系列转换为索引和值的元组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38468549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to convert pandas series to tuple of index and value
提问by piRSquared
I'm looking for an efficient way to convert a series to a tuple of its index with its values.
我正在寻找一种有效的方法将系列转换为其索引的元组及其值。
s = pd.Series([1, 2, 3], ['a', 'b', 'c'])
I want an array, list, series, some iterable:
我想要一个数组,列表,系列,一些可迭代的:
[(1, 'a'), (2, 'b'), (3, 'c')]
回答by Divakar
Well it seems simply zip(s,s.index)
works too!
好吧,它似乎也很zip(s,s.index)
有效!
For Python-3.x, we need to wrap it with list
-
对于 Python-3.x,我们需要用list
-
list(zip(s,s.index))
To get a tuple of tuples, use tuple()
: tuple(zip(s,s.index))
.
要获取元组的元组,请使用tuple()
: tuple(zip(s,s.index))
。
Sample run -
样品运行 -
In [8]: s
Out[8]:
a 1
b 2
c 3
dtype: int64
In [9]: list(zip(s,s.index))
Out[9]: [(1, 'a'), (2, 'b'), (3, 'c')]
In [10]: tuple(zip(s,s.index))
Out[10]: ((1, 'a'), (2, 'b'), (3, 'c'))
回答by abeboparebop
One possibility is to swap the order of the index elements and the values from iteritems
:
一种可能性是交换索引元素的顺序和来自 的值iteritems
:
res = [(val, idx) for idx, val in s.iteritems()]
EDIT: @Divakar's answer is faster by about a factor of 2. Building a series?of random strings for testing:
编辑:@Divakar 的答案快了大约 2 倍。构建一系列随机字符串进行测试:
N = 100000
str_len = 4
ints = range(N)
strs = [None]*N
for i in ints:
strs[i] = ''.join(random.choice(string.ascii_letters) for _ in range(str_len))
s = pd.Series(ints, strs)
Timings:
时间:
%timeit res = zip(s,s.index)
>>> 100 loops, best of 3: 14.8 ms per loop
%timeit res = [(val, idx) for idx, val in s.iteritems()]
>>> 10 loops, best of 3: 26.7 ms per loop
回答by smci
s.items()
or s.iteritems()
do this.
s.items()
或s.iteritems()
这样做。
(If you want to get the output as a list rather than an iterator list(s.items())
)
(如果您想将输出作为列表而不是迭代器list(s.items())
)