我想打印出C和C1以及braf列中有1的其他行名。所以我希望我的输出是C,C1,。。。
'Braf'
'C' 1
'NC' 0
'C1' 1
... ...
如果您想要在特定列中具有特定值的行的索引,可以使用groupby
:
df = pd.DataFrame({'BRAF': [0,1,0,1,1]})
d = df.index.groupby(df['BRAF'].eq(1))
# you can also directly use 0/1 if binary
groupA = d[True]
# [0, 2]
groupB = d[False]
# [1, 3, 4]
或者直接作为字典:
out = df.index.groupby(np.where(df['BRAF'].eq(1), 'groupA', 'groupB'))
输出:
{'groupA': [1, 3, 4],
'groupB': [0, 2]}
如果需要索引值,如果匹配列Braf
,则使用:
m = df['Braf'] == 1
groupA, groupbB = df.index[m].tolist(), df.index[~m].tolist()
如果需要,获取列0
:的值
m = df['Braf'] == 1
groupA, groupbB = df.loc[m, 0].tolist(), df.loc[~m, 0].tolist()
如果需要按第一列提取值:
m = (df['Braf'] == 1).to_numpy()
groupA, groupbB = df.iloc[m, 0].tolist(), df.iloc[~m, 0].tolist()
编辑:
df = pd.DataFrame({'col':['a','b','c'],
'Braf':[1,0, 1]}, index=['C','NC','C1'])
print (df)
col Braf
C a 1
NC b 0
C1 c 1
#labels of indices
print (df.index)
Index(['C', 'NC', 'C1'], dtype='object')
#first column - selected by position - labels are same
print (df.iloc[:, 0])
C a
NC b
C1 c
Name: col, dtype: object
#column Braf - labels are same
print (df['Braf'])
C 1
NC 0
C1 1
Name: Braf, dtype: int64