Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
91 views
in Technique[技术] by (71.8m points)

python - Pandas appy alternative

I am looking to use option #2 to get the result of option #1.

import pandas as pd

df=pd.DataFrame(np.arange(50), columns=['A'])

def test(x):
  v=30
  if v>x:
    return(x)

#option 1
df['A'].apply(lambda x: test(x))

#option 2
test(df['A'])
question from:https://stackoverflow.com/questions/65838053/pandas-appy-alternative

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The error message that I get when I run your code says:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(). 

The problem is that a is an array and v a single value, so there is no single truth value in the comparison. If you intention is to check if v is greater than all numbers in a, use np.all(v>a). If you want to check if v is greater than just some use np.any(v>a).

On Edit

You have now edited your question so much that it is now a new question. The entire point of the apply method is that if f is a Python function and v is a numpy array, then f(v) is probably not the array that you would get by applying f to the elements of v. Python is not a language that directly supports vectorized calculations. The reason that it sometimes seems that computations in numpy or pandas are as easy to vectorize as similar calculations in e.g. R is because of the way Python's duck-typing works. If a class defines the magic method __add__ then you can use + to add elements of that class to each other in any way that you want. This is exactly what the people who created numpy have done (as well as other magic methods for things like *,/,< etc.) So, if a function definition is something like def f(x): return x*x + 2*x + 3 where all the computational steps correspond to magic methods, then v.apply(f) and f(v) will work the same. Your test function uses the keyword if. There is not a magic method which can convert that part of the core language into something else.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...