getting the index of a row in a pandas apply function

后端 未结 3 1634
灰色年华
灰色年华 2020-11-29 21:48

I am trying to access the index of a row in a function applied across an entire DataFrame in Pandas. I have something like this:

df = pandas.Dat         


        
3条回答
  •  抹茶落季
    2020-11-29 22:38

    Either:

    1. with row.name inside the apply(..., axis=1) call:

    df = pandas.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'], index=['x','y'])
    
       a  b  c
    x  1  2  3
    y  4  5  6
    
    df.apply(lambda row: row.name, axis=1)
    
    x    x
    y    y
    

    2. with iterrows() (slower)

    DataFrame.iterrows() allows you to iterate over rows, and access their index:

    for idx, row in df.iterrows():
        ...
    

提交回复
热议问题