Pandas apply custom function to DF

2024/9/20 5:25:31

I would like to create a brand new data frame by replacing values of a DF using a custom function. I keep getting the following error "ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()."

I tried some suggestions (Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()) but it didn't work.

I would appreciate if somebody could shed light on this issue and help me out. Thank you in advance for your time.

def convert2integer(x):if x <= -0.5:return -1elif (x > -0.5 & x <= 0.5):return 0elif x > 0.5:return 1df = pd.DataFrame({'A':[1,0,-0.6,-1,0.7],'B':[-1,1,-0.3,0.5,1]})df.apply(convert2integer)
Answer

A few options:

  1. The slower option but the most similar via applymap:
def convert2integer(x):if x <= -0.5:return -1elif x <= 0.5:return 0else:return 1df = pd.DataFrame({'A': [1, 0, -0.6, -1, 0.7],'B': [-1, 1, -0.3, 0.5, 1]})new_df = df.applymap(convert2integer)

new_df:

   A  B
0  1 -1
1  0  1
2 -1  0
3 -1  0
4  1  1

applymap applies the function to each cell in the DataFrame. For this reason, x is a float, and should be treated as such.

  1. The faster option via np.select:
import numpy as np
import pandas as pddf = pd.DataFrame({'A': [1, 0, -0.6, -1, 0.7],'B': [-1, 1, -0.3, 0.5, 1]})new_df = pd.DataFrame(np.select([df.le(-0.5), df.le(0.5)],[-1, 0],default=1),index=df.index,columns=df.columns
)

new_df:

   A  B
0  1 -1
1  0  1
2 -1  0
3 -1  0
4  1  1

np.select takes a list of conditions, and a list of choices. When the condition is True it uses the values from the corresponding index in the choice list.

The last condition does not need checked as if it did not match the first two conditions it must be greater than 0.5. Likewise, the second condition does not need to also check that it is greater than -0.5 because if it were the first condition would have been met.

https://en.xdnf.cn/q/119771.html

Related Q&A

Economy Bot Daily Streak

I have a Discord.py economy bot that includes a daily command It gives everyone each day $50, but there is also a streak system. The first time they claim their daily, the bot gives them $50, day 2 is …

Normalise JSON with Python

Prompt me, please, how to normalize this JSON file using Python? This question is related to the previous The current JSON contains: {"total_stats": [{"domain": "domain.com&qu…

How to change decimal separator?

I have an Excel spreadsheet (an extract from SAP). I turn this into a DataFrame, do calculations and save it to an SQLite database. The Excel spreadsheet has comma as decimal separator. The SQLite data…

Unable to scrape the name from the inner page of each result using requests

Ive created a script in python making use of post http requests to get the search results from a webpage. To populate the results, it is necessary to click on the fields sequentially shown here. Now a …

Python Integer and String Using [duplicate]

This question already has an answer here:How can I concatenate str and int objects?(1 answer)Closed 7 years ago.for size in [1, 2, 3, 4]:result = 0print("size=" + str(size))for element in ra…

Beginner to python: Lists, Tuples, Dictionaries, Sets [duplicate]

This question already has an answer here:What is the difference between lists,tuples,sets and dictionaries? [closed](1 answer)Closed 3 years ago.I have been trying to understand what the difference is…

TypeError: NoneType object is not iterable in Python in csv

I am new to python, and trying to create a program which opens a csv file. The user is supposed to enter a barcode , then the program finds that product and the cost of the product. However I got an er…

No such Element Exception using selenium in python

from selenium import webdriver from selenium.webdriver.common.keys import Keys chrome_path=r"C:\Users\Priyanshu\Downloads\Compressed\chromedriver_win32\chromedriver.exe" driver=webdriver.Chro…

Web scraping, cant get the href of a tag

Im trying to scrape this Page https://rarity.tools/thecryptodads Using Selenium in python. At the top of the right of each card below, theres the owner name that contains a link once pressed, it takes …

Using Python Pandas to fill new table with NaN values

Ive imported data from a csv file which has columns NAME, ADDRESS, PHONE_NUMBER. Sometimes, at least 1 of the columns has a missing value for that row. e.g0 - Bill, Flat 2, 555123 1 - Katie, NaN, NaN 2…