Skip to main content
 首页 » 编程设计

python之在python中通过其索引和数组切片数据框

2025年05月04日10yjmyzz

我有一个示例数据框 df 和一个数组 n ,如下所示。我想根据索引中的数组值进行过滤。输出数据框也如下所示。我试过 Out = df[df.index == n] , Out = df.loc[df.index == n] 和 df.loc[ n] 不起作用,给出错误 Lengths must match to compare。谁能帮我解决这个问题。这里的数组是数据框对应的行号。

df =  
             Open   High    Low    Close    Adj Close   Volume 
2007-06-18  0.33979 0.33979 0.33979 0.33979 0.33979 1591888 
2007-06-29  0.33074 0.33074 0.33074 0.33074 0.33074 88440 
2007-06-20  0.33526 0.33526 0.33526 0.33526 0.33526 3538 
2007-06-21  0.32113 0.32113 0.32113 0.32113 0.32113 3550 
2007-06-22  0.34713 0.34713 0.34713 0.34713 0.34713 670 
2007-06-16  0.33979 0.33979 0.33979 0.33979 0.33979 1591888 
2007-06-30  0.33074 0.33074 0.33074 0.33074 0.33074 88440 
2007-06-31  0.33526 0.33526 0.33526 0.33526 0.33526 3538 
2007-06-44  0.32113 0.32113 0.32113 0.32113 0.32113 3550 
2007-06-22  0.34713 0.34713 0.34713 0.34713 0.34713 670 
 
n = array([0, 1, 2, 3]) 
 
Out  =  
            Open      High  Low     Close   Adj Close   Volume 
2007-06-18  0.33979 0.33979 0.33979 0.33979 0.33979 1591888 
2007-06-29  0.33074 0.33074 0.33074 0.33074 0.33074 88440 
2007-06-20  0.33526 0.33526 0.33526 0.33526 0.33526 3538 
2007-06-21  0.32113 0.32113 0.32113 0.32113 0.32113 3550 

请您参考如下方法:

使用DataFrame.iloc按职位选择:

n = np.array([     0,      1,      2, 3]) 
df = df.iloc[n] 
print (df) 
               Open     High      Low    Close  Adj Close   Volume 
2007-06-18  0.33979  0.33979  0.33979  0.33979    0.33979  1591888 
2007-06-29  0.33074  0.33074  0.33074  0.33074    0.33074    88440 
2007-06-20  0.33526  0.33526  0.33526  0.33526    0.33526     3538 
2007-06-21  0.32113  0.32113  0.32113  0.32113    0.32113     3550