Pandas how to get the index of row?

2683 views python
0

import pandas as pd
data = pd.read_csv('traj2_Binarization.csv', sep=",", index_col="NAME")

for index, row in data.iterrows():
    print(row)
    -----results------
    RUNX3            0
    ROGDI            0
    FSTL3            0
    MOCOS            0
    PDCD7            1
    MYO15A           0
    MYO9B            0
    MAP1LC3A         0
    TBC1D19          0
    ASIC1            0
    RAP1A            0
    ARAP3            0
    IQSEC2           0
    HIVEP3           0

Here, how can I make the results converted to below?

RUNX3 = False
ROGDI = False
FSTL3 = False
MOCOS = False
PDCD7 = True
.
.
.

answered question

2 Answers

13

Use f-strings with selecting one item Series to scalar by row["NAME"] and converting to bool:

#python 3.6 +
for index, row in data.iterrows():
    print(f'{index} = {bool(row["NAME"])}')
#python bellow 3.6
for index, row in data.iterrows():
    print('{} = {}'.format(index, bool(row["NAME"])))

RUNX3 = False
ROGDI = False
FSTL3 = False
MOCOS = False
PDCD7 = True
MYO15A = False
MYO9B = False
MAP1LC3A = False
TBC1D19 = False
ASIC1 = False
RAP1A = False
ARAP3 = False
IQSEC2 = False
HIVEP3 = False

for index, row in data.iterrows():
    print(index, bool(row["NAME"]))

RUNX3 False
ROGDI False
FSTL3 False
MOCOS False
PDCD7 True
MYO15A False
MYO9B False
MAP1LC3A False
TBC1D19 False
ASIC1 False
RAP1A False
ARAP3 False
IQSEC2 False
HIVEP3 False

posted this
6

Additionally to @jezrael's answer, if version under 3.6:

for index, row in data.iterrows():
    print('%s = %s'%(index,bool(row['NAME'])))

Or:

for index, row in data.iterrows():
    print('{0} = {1}'.format(index,bool(row['NAME'])))

Both Output:

RUNX3 = False
ROGDI = False
FSTL3 = False
MOCOS = False
PDCD7 = True
MYO15A = False
MYO9B = False
MAP1LC3A = False
TBC1D19 = False
ASIC1 = False
RAP1A = False
ARAP3 = False
IQSEC2 = False
HIVEP3 = False

posted this

Have an answer?

JD

Please login first before posting an answer.