2017-02-15 15 views
2

我發現了大約.at.iat用於快速標量索引的pandas DataFrame的方法。在大熊貓上使用`.at`或`.iat`標量訪問方法和布爾索引DataFrames

http://pandas.pydata.org/pandas-docs/stable/indexing.html#fast-scalar-value-getting-and-setting

有沒有辦法將它們與布爾索引結合?

In [1]: import pandas as pd 

In [2]: data = { 
    ...: "A": [1, 2], 
    ...: "B": [3, 4] 
    ...: } 

In [3]: df = pd.DataFrame(data) 

In [4]: df.index = ["x", "y"] 

In [5]: df 
Out[5]: 
    A B 
x 1 3 
y 2 4 

In [6]: df.ix[df.A == 1, "B"] 
Out[6]: 
x 3 
Name: B, dtype: int64 

In [7]: df.ix[df.A == 1, "B"].values[0] 
Out[7]: 3 

In [8]: df.at["x", "B"] 
Out[8]: 3 

In [9]: df.at[df.A == 1, "B"] 
--------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 
<ipython-input-9-e2b7f23503ca> in <module>() 
----> 1 df.at[df.A == 1, "B"] 

/home/jlcano/.miniconda3/envs/py36/lib/python3.6/site-packages/pandas/core/indexing.py in __getitem__(self, key) 
    1663 
    1664   key = self._convert_key(key) 
-> 1665   return self.obj.get_value(*key, takeable=self._takeable) 
    1666 
    1667  def __setitem__(self, key, value): 

/home/jlcano/.miniconda3/envs/py36/lib/python3.6/site-packages/pandas/core/frame.py in get_value(self, index, col, takeable) 
    1898   series = self._get_item_cache(col) 
    1899   engine = self.index._engine 
-> 1900   return engine.get_value(series.get_values(), index) 
    1901 
    1902  def set_value(self, index, col, value, takeable=False): 

pandas/index.pyx in pandas.index.IndexEngine.get_value (pandas/index.c:3557)() 

pandas/index.pyx in pandas.index.IndexEngine.get_value (pandas/index.c:3240)() 

pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:3986)() 

TypeError: 'x  True 
y False 
Name: A, dtype: bool' is an invalid key 

這是最簡單的解決方案,我發現:

In [10]: df.at[df[df.A == 1].index.tolist()[0], "B"] 
Out[10]: 3 

回答

1

IIUC你能做到這樣:

In [131]: df 
Out[131]: 
    A B 
x 1 3 
y 2 4 
z 1 5 

In [132]: df.at[(df.A == 1).idxmax(), 'B'] 
Out[132]: 3 
+0

不知道了'idxmax'功能,非常感謝! – astrojuanlu