不太清楚为什么我无法解决这个问题.我正在寻找使用索引号切片Pandas数据帧.我有一个列表/核心索引,其中包含我不需要的索引号,如下所示
pandas.core.index.Int64Index
Int64Index([2340, 4840, 3163, 1597, 491 , 5010, 911 , 3085, 5486, 5475, 1417, 2663, 4204, 156 , 5058, 1990, 3200, 1218, 3280, 793 , 824 , 3625, 1726, 1971, 2845, 4668, 2973, 3039, 376 , 4394, 3749, 1610, 3892, 2527, 324 , 5245, 696 , 1239, 4601, 3219, 5138, 4832, 4762, 1256, 4437, 2475, 3732, 4063, 1193], dtype=int64)
Run Code Online (Sandbox Code Playgroud)
如何创建除这些索引号之外的新数据帧.我试过了
df.iloc[combined_index]
Run Code Online (Sandbox Code Playgroud)
显然这只是显示那些索引号的行(与我想要的相反).任何帮助将不胜感激
Vor*_*Vor 49
不确定这是否是您要找的,将其作为答案发布,因为评论太长了:
In [31]: d = {'a':[1,2,3,4,5,6], 'b':[1,2,3,4,5,6]}
In [32]: df = pd.DataFrame(d)
In [33]: bad_df = df.index.isin([3,5])
In [34]: df[~bad_df]
Out[34]:
a b
0 1 1
1 2 2
2 3 3
4 5 5
In [35]:
Run Code Online (Sandbox Code Playgroud)
All*_*ang 14
可能更简单的方法是使用布尔索引,然后切片通常执行以下操作:
df[~df.index.isin(list_to_exclude)]
Run Code Online (Sandbox Code Playgroud)
只需使用.drop并将其传递给索引列表即可排除。
import pandas as pd
df = pd.DataFrame({"a": [10, 11, 12, 13, 14, 15]})
df.drop([1, 2, 3], axis=0)
Run Code Online (Sandbox Code Playgroud)
哪个输出。
a
0 10
4 14
5 15
Run Code Online (Sandbox Code Playgroud)
您可以pd.Int64Index(np.arange(len(df))).difference(index)用来形成新的序数索引。例如,如果我们要删除与序数索引[1,3,5]相关联的行,则
import numpy as np
import pandas as pd
index = pd.Int64Index([1,3,5], dtype=np.int64)
df = pd.DataFrame(np.arange(6*2).reshape((6,2)), index=list('ABCDEF'))
# 0 1
# A 0 1
# B 2 3
# C 4 5
# D 6 7
# E 8 9
# F 10 11
new_index = pd.Int64Index(np.arange(len(df))).difference(index)
print(df.iloc[new_index])
Run Code Online (Sandbox Code Playgroud)
产量
0 1
A 0 1
C 4 5
E 8 9
Run Code Online (Sandbox Code Playgroud)