Pandas-Obtener el valor de la primera fila de una columna dada


Esto parece una pregunta ridículamente fácil... pero no veo la respuesta fácil que esperaba.

Entonces, ¿cómo obtengo el valor en una enésima fila de una columna dada en Pandas? (Estoy particularmente interesado en la primera fila, pero estaría interesado en una práctica más general también).

Por ejemplo, digamos que quiero extraer el valor 1.2 en Btime como una variable.

¿Cuál es la manera correcta de hacer esto?

Df_test =

  ATime   X   Y   Z   Btime  C   D   E
0    1.2  2  15   2    1.2  12  25  12
1    1.4  3  12   1    1.3  13  22  11
2    1.5  1  10   6    1.4  11  20  16
3    1.6  2   9  10    1.7  12  29  12
4    1.9  1   1   9    1.9  11  21  19
5    2.0  0   0   0    2.0   8  10  11
6    2.4  0   0   0    2.4  10  12  15
Author: smci, 2014-08-12

5 answers

Para seleccionar la fila ith, use iloc:

In [31]: df_test.iloc[0]
Out[31]: 
ATime     1.2
X         2.0
Y        15.0
Z         2.0
Btime     1.2
C        12.0
D        25.0
E        12.0
Name: 0, dtype: float64

Para seleccionar el valor i en la columna Btime puede usar:

In [30]: df_test['Btime'].iloc[0]
Out[30]: 1.2

Advertencia : Yo había sugerido previamente df_test.ix[i, 'Btime']. Pero esto no garantiza que le dé el valor ith ya que ix intenta indexar por label antes de intentar indexar por position. Así que si el DataFrame tiene un índice entero que no está en orden ordenado a partir de 0, entonces usando ix[i] devolverá la fila etiquetado i en lugar de la fila ith. Por ejemplo,

In [1]: df = pd.DataFrame({'foo':list('ABC')}, index=[0,2,1])

In [2]: df
Out[2]: 
  foo
0   A
2   B
1   C

In [4]: df.ix[1, 'foo']
Out[4]: 'C'
 211
Author: unutbu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-12 08:46:33

Tenga en cuenta que la respuesta de @unutbu será correcta hasta que desee establecer el valor en algo nuevo, entonces no funcionará si su dataframe es una vista.

In [4]: df = pd.DataFrame({'foo':list('ABC')}, index=[0,2,1])
In [5]: df['bar'] = 100
In [6]: df['bar'].iloc[0] = 99
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas-0.16.0_19_g8d2818e-py2.7-macosx-10.9-x86_64.egg/pandas/core/indexing.py:118: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame

See the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self._setitem_with_indexer(indexer, value)

Otro enfoque que funcionará consistentemente tanto con la configuración como con la obtención es:

In [7]: df.loc[df.index[0], 'foo']
Out[7]: 'A'
In [8]: df.loc[df.index[0], 'bar'] = 99
In [9]: df
Out[9]:
  foo  bar
0   A   99
2   B  100
1   C  100
 16
Author: andrew,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-19 18:42:35
  1. df.iloc[0].head(1) - Primer conjunto de datos solo de toda la primera fila.
  2. df.iloc[0] - Toda la primera fila de la columna.
 6
Author: nikhil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-25 13:17:35

Otra forma de hacer esto:

first_value = df['Btime'].values[0]

Esta forma parece ser más rápida que usar .iloc:

In [1]: %timeit -n 1000 df['title'].values[20]
5.82 µs ± 142 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [2]: %timeit -n 1000 df['title'].iloc[20]
29.2 µs ± 1.28 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
 4
Author: Abdo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-28 17:23:21

De manera general, si desea recoger las primeras N filas de la columna J de pandas dataframe, la mejor manera de hacerlo es:

Data = dataframe [0: N] [:, J]

 1
Author: anis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-01 17:47:45