【问题标题】:Access value by location in sorted pandas series with integer index在具有整数索引的已排序熊猫系列中按位置访问值
【发布时间】:2013-01-22 09:55:52
【问题描述】:

我有一个带有整数索引的 pandas 系列,我已经(按值)排序,我如何在这个系列中按位置访问值。

例如:

s_original = pd.Series({0: -0.000213, 1: 0.00031399999999999999, 2: -0.00024899999999999998, 3: -2.6999999999999999e-05, 4: 0.000122})
s_sorted = np.sort(s_original)

In [3]: s_original
Out[3]: 
0   -0.000213
1    0.000314
2   -0.000249
3   -0.000027
4    0.000122

In [4]: s_sorted
Out[4]: 
2   -0.000249
0   -0.000213
3   -0.000027
4    0.000122
1    0.000314

In [5]: s_sorted[3]
Out[5]: -2.6999999999999999e-05

但我想获得 0.000122 的值,即 position 3 中的项目。
我该怎么做?

【问题讨论】:

    标签: python pandas series


    【解决方案1】:

    换行

    b = np.sort(a)
    

    b = pd.Series(np.sort(a), index=a.index)
    

    这将对值进行排序,但保留索引。

    编辑:

    获取排序后的Series中的第四个值:

    np.sort(a).values[3]
    

    【讨论】:

    • 我用这个 sample_mean_series_sorted = pandas.Series(np.sort(sample_mean_series), index=sample_mean_series.index) 交换了行。但它没有解决我的问题。为了清除,我想检索已排序系列中的特定行。例如,获取第四行的值为 0.000122。
    【解决方案2】:

    您可以使用iget 按位置检索:
    (实际上,创建此方法是为了克服这种歧义。)

    In [1]: s = pd.Series([0, 2, 1])
    
    In [2]: s.sort()
    
    In [3]: s
    Out[3]: 
    0    0
    2    1
    1    2
    
    In [4]: s.iget(1)
    Out[4]: 1
    

    .

    .ix 带有整数索引的行为在pandas "gotchas" 中注明:

    在 pandas 中,我们的一般观点是标签比整数位置更重要。因此,对于整数轴索引,使用.ix 等标准工具只能进行基于标签的索引。

    做出这一深思熟虑的决定是为了防止歧义和微妙的错误(许多用户报告在 API 更改以停止“退回”基于位置的索引时发现错误)。

    注意:如果您使用的是非整数索引,这工作,其中.ix 不模糊。

    例如:

    In [11]: s1 = pd.Series([0, 2, 1], list('abc'))
    
    In [12]: s1
    Out[12]: 
    a    0
    b    2
    c    1
    
    In [13]: s1.sort()
    
    In [14]: s1
    Out[14]: 
    a    0
    c    1
    b    2
    
    In [15]: s1.ix[1]
    Out[15]: 1
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-19
    • 2016-02-06
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 2019-02-19
    • 1970-01-01
    • 2019-06-29
    相关资源
    最近更新 更多