【问题标题】:Filter DataFrame for numeric valuesFilter DataFrame for numeric values
【发布时间】:2022-12-01 21:03:02
【问题描述】:

Let's assume my DataFrame df has a column called col of type string. What is wrong with the following code line?

df['col'].filter(str.isnumeric)

【问题讨论】:

    标签: python pandas filter numeric


    【解决方案1】:

    You can do it like that:

    df.loc[df['col'].str.isnumeric()]
    

    【讨论】:

    • Thanks, that is a short and good solution to what I wanted to achieve. However, since I want to learn pandas better I'm interested: Is there a solution to the problem using the pandas filter method?
    【解决方案2】:

    First problem, you're using abuilt-inpython method without parenthesis which is str.isnumeric. Hence, the TypeError: 'method_descriptor' object is not iterable.

    Second problem, let's suppose you've added parenthesis to str.isnumeric, this function needs one argument/string to check if all characters in the given string are numeric characters. Hence the TypeError: unbound method str.isnumeric() needs an argument.

    Third problem, let's suppose you've fixed1)and2), since this function returns a boolean (TrueorFalse), you cannot pass it as a first parameter of pandasbuilt-inmethod pandas.Series.filter. Hence, the TypeError: 'bool' object is not iterable.

    As per the documentation, the first parameter needs to be a list-like :

    items: list-like
    Keep labels from axis which are in items.

    In your case, I believe you want to use boolean indexing with pandas.DataFrame.loc :

    import pandas as pd
    
    df = pd.DataFrame({'col': ['foo', 'bar 123', '456']})
    m = df['col'].str.isnumeric()
    out = df.loc[m]
    

    Output:

    print(out)
       col
    2  456
    

    【讨论】:

    • Thanks for your answer. What do you mean with "without parenthesis". Do you mean those at the end like str.isnumeric()?
    • Yes, those are the parenthesis I'm talking about.
    • In order to learn pandas better I'm looking for a solution using the filter method. I also tried to use a lambda expression. Can you make my filtering work with the pandas filter method even though masking is of course a lot easier?
    猜你喜欢
    • 2022-12-01
    • 2022-12-02
    • 2012-10-04
    • 1970-01-01
    • 2015-10-17
    • 1970-01-01
    • 2022-12-28
    • 2022-12-02
    • 1970-01-01
    相关资源
    最近更新 更多