[英]Select the inverse index in pd.Dataframe
如何使用loc
或iloc
在 pd.DataFrame 中選擇反向索引?
我試過df.loc[!my_index,my_feature]
但失敗了。
而df.loc[[ind for ind in df.index.tolist() if ind not in my_index],my_feature]
看起來太單調了。 有什么更好的主意嗎?
使用difference
:
df.loc[df.index.difference(my_index),my_feature]
或者numpy.setdiff1d
:
df.loc[np.setdiff1d(df.index, my_index),my_feature]
樣品:
my_index = [5,7]
df = pd.DataFrame({'A': ['a','a','a','b'], 'B': list(range(4)) }, index=[5,7,8,9])
print (df)
A B
5 a 0
7 a 1
8 a 2
9 b 3
print(df.loc[df.index.difference(my_index),'A'])
8 a
9 b
Name: A, dtype: object
您可以利用index.difference
。
idx2 = df.index.difference(my_index)
或者, set.difference
idx2 = set(df.index).difference(my_index) # note, order not guaranteed
df.loc[idx2, ...]
假設 my_index 是您要忽略的行索引,您可以將它們刪除在數據幀 df 中存在的位置:
df = df.drop(my_index, errors='ignore')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.