【发布时间】: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
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
You can do it like that:
df.loc[df['col'].str.isnumeric()]
【讨论】:
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
【讨论】:
str.isnumeric()?