Python Pandas iterate over rows and access column names

前端 未结 4 1264
南笙
南笙 2020-12-03 00:35

I am trying to iterate over the rows of a Python Pandas dataframe. Within each row of the dataframe, I am trying to to refer to each value along a row by its column name.

4条回答
  •  渐次进展
    2020-12-03 01:26

    I also like itertuples()

    for row in df.itertuples():
        print(row.A)
        print(row.Index)
    

    since row is a named tuples, if you meant to access values on each row this should be MUCH faster

    speed run :

    df = pd.DataFrame([x for x in range(1000*1000)], columns=['A'])
    st=time.time()
    for index, row in df.iterrows():
        row.A
    print(time.time()-st)
    45.05799984931946
    
    st=time.time()
    for row in df.itertuples():
        row.A
    print(time.time() - st)
    0.48400020599365234
    

提交回复
热议问题