如何获取行的索引?

2024-05-19 12:05:01 发布

您现在位置:Python中文网/ 问答频道 /正文

enter image description here

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

在这里,如何将结果转换为下面的?你知道吗

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

Tags: csvimportfalsepandasreaddataindexas
2条回答

除@jezrael的答案外,如果版本低于3.6:

for index, row in data.iterrows():
    print('%s = %s'%(index,bool(row['whatever is the column'])))

或:

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

或:

for index, row in data.iterrows():
    print(index,'=',bool(row['whatever is the column']))

所有输出:

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

使用f-string通过row["NAME"]选择一个要标量的项序列并转换为bool

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

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["RUNX3"]))

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

对于布尔值Series,使用^{}

s = data["RUNX3"].astype(bool)
print (s)
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
Name: NAME, dtype: bool

相关问题 更多 >

    热门问题