[英]How do I delete a row in Pandas dataframe when a specific column contains a value that signals to me that the row should be deleted?
[英]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.