python - 如何对具有多索引的系列使用 pandas .at 函数
问题描述
我正在使用 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
推荐阅读
- php - php firebase 通知示例
- visual-studio-code - VSCode API:特定行的内联输入
- ios - Windows 中的“cordova run ios”不起作用
- google-maps - 如何为 Google 地图购买位置配额
- html - 具有左上边距的浮动框,具有垂直对齐和字体大小的响应式文本 div
- reactjs - 从 firebase 查询返回数据
- angular - Angular 7 Protractor 非 Angular 登录页面
- php - 如何将迭代器发送到 laravel 队列作业
- mysql - MySQL 更新表 WHERE 列中的另一个是
- google-apps-script - 有没有办法从 Google Doc 中的图像、按钮或链接调用 myFunction(),而不是使用菜单?