繁体   English   中英

如何使用 python 和 Pandas 检查行是否在特定列名处包含 1

[英]How do I check to see if a row contains a 1 at a specific column name using python with Pandas

我想打印出 C 和 C1 以及 braf 列中具有 1 的其他行名称。 所以我希望我的 output 是 C,C1,...

      'Braf'
'C'      1     
'NC'     0
'C1'     1
...      ...

如果匹配列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

如果您想要在特定列中具有特定值的行的索引,您可以使用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'))

Output:

{'groupA': [1, 3, 4],
 'groupB': [0, 2]}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM