Pandas - Get first row value of a given column

前端 未结 7 1914
甜味超标
甜味超标 2020-11-28 18:05

This seems like a ridiculously easy question... but I\'m not seeing the easy answer I was expecting.

So, how do I get the value at an nth row of a given column in Pa

7条回答
  •  眼角桃花
    2020-11-28 18:24

    Note that the answer from @unutbu will be correct until you want to set the value to something new, then it will not work if your dataframe is a view.

    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)
    

    Another approach that will consistently work with both setting and getting is:

    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
    

提交回复
热议问题