Skip to main content
 首页 » 编程设计

python之如何将 pandas .at 函数用于具有多索引的系列

2024年11月24日9Leo_wl

我正在使用 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 吗?

请您参考如下方法:

使用Series.loc :

print (s.loc[("bar","one")]) 
1.265936258705534 

编辑:

看来是bug。

如果使用 DataFrame,它工作得很好:

np.random.seed(1234) 
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) 
print (s) 
first  second 
bar    one       0.471435 
       two      -1.190976 
baz    one       1.432707 
       two      -0.312652 
foo    one      -0.720589 
       two       0.887163 
qux    one       0.859588 
       two      -0.636524 
dtype: float64 
 
df = s.to_frame('col') 
print (df) 
                   col 
first second           
bar   one     0.471435 
      two    -1.190976 
baz   one     1.432707 
      two    -0.312652 
foo   one    -0.720589 
      two     0.887163 
qux   one     0.859588 
      two    -0.636524 
 
print (df.at[("bar","one"), 'col']) 
0.47143516373249306