【问题标题】:How do I create a DataFrame containing a column where rows are greater than a number?如何创建包含行大于数字的列的 DataFrame?
【发布时间】:2016-10-12 05:11:28
【问题描述】:

我有一个包含这些列的 DataFrame:

ID                    int64
Key                   int64
Reference            object
sKey                float64
sName               float64
fKey                 int64
cName                object
ints                  int32

我想创建一个包含列commonNameints 的新DataFrame,其中ints 大于10,我正在这样做:

df_greater_10 = df[['commonName', df[df.ints >= 1997]]]

我看到问题出在表达式 df[df.ints >= 1997] 上,因为我正在返回一个 DataFrame - 我怎样才能获得值大于 10 的 ints 列?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以使用许多可用的indexers 之一。我会推荐.ix,因为它似乎是faster

    df_greater_10 = df.ix[df.ints >= 1997, ['commonName', 'ints']]
    

    或者如果您只需要ints

    df_greater_10 = df.ix[df.ints >= 1997, 'ints']
    

    演示:

    In [123]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))
    
    In [124]: df
    Out[124]:
        a   b   c
    0  13  11  14
    1  14  10  13
    2   7  11   6
    3   7  13  12
    4   9   9   6
    5   7   7   7
    6   5   7   8
    7   5  11   5
    8   9   7   9
    9  11  13   7
    
    In [125]: df_greater_10 = df.ix[df.c > 10, ['a','c']]
    
    In [126]: df_greater_10
    Out[126]:
        a   c
    0  13  14
    1  14  13
    3   7  12
    

    更新: 从 Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers 开始。

    所以使用df.loc[...]df.iloc[...] 而不是已弃用的df.ix[...]

    【讨论】:

    • 我试过了,但我得到了一个例外ValueError: cannot copy sequence with size 13 to array axis with dimension 19106
    • @NRKirby,抱歉,我的代码中有错字,现在应该可以使用了
    • 非常感谢@MaxU !!
    • @NRKirby,我总是很乐意提供帮助! :)
    【解决方案2】:

    不知道你为什么没有先尝试df[df.ints >= 1997]['ints'](也许我遗漏了一些东西,你的数据框很大?)。下面是它如何工作的演示

    >>> pd.DataFrame({'ints': [1, 2, 3, 10, 11], 'other': ['a', 'b', 'c', 'y', 'z']})
    
    ', 'y', 'z']})
       ints other
    0     1     a
    1     2     b
    2     3     c
    3    10     y
    4    11     z
    
    >>> df[df.ints >= 10]
       ints other
    3    10     y
    4    11     z
    >>> df[df.ints >= 10]['ints']
    3    10
    4    11
    

    您也可以使用df['ints'][df['ints'] >= 10] 获得相同的结果,这表明您只对ints 列感兴趣。

    【讨论】:

    • 你没有错过任何东西,我是 Python 新手。我试过df_greater_10 = df[['commonName' df[df.ints >= 1997]['ints']]] 但我得到ValueError: setting an array element with a sequence
    猜你喜欢
    • 1970-01-01
    • 2018-12-13
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    • 2021-12-03
    • 2023-03-24
    • 2016-12-08
    • 2019-05-14
    相关资源
    最近更新 更多