【发布时间】:2019-09-26 02:16:25
【问题描述】:
我正在使用 iterrows 遍历具有多索引的大型数据框。结果是具有多索引的系列。经过一些分析,结果发现大部分时间都花在了获取系列的单元格值上,所以我想使用 Series.at 函数,因为它更快。 不幸的是,我在 pandas 文档中没有找到关于 multiindex 的任何内容。
这是一个简单的代码:
import numpy as np
import pandas as pd
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
s = pd.Series(np.random.randn(8), index=index)
>>>>s
first second
bar one -0.761968
two 0.670786
baz one -0.193843
two -0.251533
foo one 1.732875
two 0.538561
qux one -1.111480
two 0.478322
dtype: float64
我尝试过 s.at[("bar","one")] , s.at["bar","one"],但这些都不起作用。
>>>>s.at[("bar","one")]
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Python\lib\site-packages\pandas\core\indexing.py", line 2270, in __getitem__
return self.obj._get_value(*key, takeable=self._takeable)
TypeError: _get_value() got multiple values for argument 'takeable'
>>>>s.at["bar","one"]
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Python\lib\site-packages\pandas\core\indexing.py", line 2270, in __getitem__
return self.obj._get_value(*key, takeable=self._takeable)
TypeError: _get_value() got multiple values for argument 'takeable'
有人知道在这种情况下如何使用 .at 吗?
【问题讨论】: