【问题标题】:Slicing Data Frame through its Index and array in python通过python中的索引和数组对数据框进行切片
【发布时间】:2018-12-25 06:18:22
【问题描述】:

我有一个示例数据框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

【问题讨论】:

标签: python arrays pandas dataframe indexing


【解决方案1】:

用于切片的 Pandas 表示法:

df.iloc[0:4,:]

【讨论】:

  • 感谢您的回答。你能解释一下这段代码里面发生了什么吗?我在哪里犯了错误?
  • 当然,iloc 代表整数位置,基本上,如果您的索引是从 0 到数据框的大小排序的,那么您就是在给出“位置”。所以 ;2007-06-18' 位于位置 0,要恢复该行,您可以执行 df.loc['2007-06-18',:] 或 df.iloc[0,:]。您犯的错误是您使用的是 loc 而不是 iloc。 Loc 要求您提供与数据帧索引相同数据类型的索引,这就是 df.loc[n] 不起作用的原因
【解决方案2】:

使用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

【讨论】:

    【解决方案3】:

    用您的输入替换 之间的所有内容

    # slice by column position
    df.iloc[<start_row>:<end_row>, <column_start_position>:<column_end_position>]
    # for everything in a column
    df.iloc[:, <column_position>]
    
    
    # slice by column name
    df.loc[<start_row>:<end_row>, <column_name>]
    # for everything in a column
    df.loc[:, <column_name>]
    

    也可以在 pandas 文档中查看 Index and Selecting Data。超级信息,如果不是在第一次通过时有点混乱。

    【讨论】:

      猜你喜欢
      • 2014-07-04
      • 2018-10-05
      • 1970-01-01
      • 2015-02-11
      • 2014-04-04
      • 1970-01-01
      • 2017-02-13
      • 2021-12-07
      • 2017-11-24
      相关资源
      最近更新 更多