How to use pandas tool to output the index value of each row and its corresponding row data

  • 2021-10-13 08:05:34
  • OfStack

Let's introduce how to use pandas tool to output the index value of each line and its corresponding line data. First, let's show the output results. Interested friends can refer to the specific example code.

Output result

name object
ID object
age object
sex object
hobbey object
dtype: object
name ID age sex hobbey
0 Bob 1 NaN Men Play Basketball
1 LiSa 2 28 Women Play Badminton
2 Mary 38 women play table tennis
3 Alan None None
-----------------------------------------
0 ['Bob', 1, nan, 'Male', 'Playing Basketball']
1 ['LiSa', 2, 28, 'Female', 'Playing Badminton']
2 ['Mary', '', 38, 'Female', 'Playing Table Tennis']
3 ['Alan', None, '', None, '']

Implementation code


import pandas as pd
import numpy as np
 
contents={"name": ['Bob',    'LiSa',           'Mary',            'Alan'],
     "ID":  [1,       2,             ' ',             None],  #  Output  NaN
     "age": [np.nan,    28,              38 ,             '' ],  #  Output  
#      "born": [pd.NaT,   pd.Timestamp("1990-01-01"), pd.Timestamp("1980-01-01"),    ''], #  Output  NaT
     "sex": [' Male ',     ' Female ',            ' Female ',            None,],  #  Output  None
     "hobbey":[' Play basketball ',   ' Play badminton ',          ' Play table tennis ',          '',],  #  Output  
     }
data_frame = pd.DataFrame(contents)
data_frame.to_excel("data_Frame.xls")
print(data_frame.dtypes)
print(data_frame)
print('-----------------------------------------')
data_frame_temp=data_frame.copy()
 
 
# Py Yeah pandas : Use pandas The tool outputs the index value of each row and its corresponding row data 
for index, row in data_frame.iterrows():   
  row_lists=list(row)
  print(index,row_lists)

Related articles: