I have a pandas table and I want to do the following mathematics operation:
|label| area | equivalent_diameter| mean_intensity| solidity|
---------------------------------------------------------------
1 1011 35.878199 255.0 0.863365:
2 107 11.672045 255.0 0.849206
3 8 3.191538 76.0 0.800000
4 18 4.787307 255.0 0.720000
5 110 11.834541 255.0 0.769231
----------------------------------------------------------------
Basically I want to:
df['area'] = math.sqrt(df['area]/math.pi)
TypeError: cannot convert the series to <class 'float'>
What I did and does not solve the problem:
new_data = df['area'].apply(lambda x: float(x))
# and then:
new_x = new_data/math.pi
new_y = math.sqrt(new_x)
still given the same error.
CodePudding user response:
Try with numpy:
import numpy as np
df['area'] = np.sqrt(df['area']/np.pi)
CodePudding user response:
You can use the List comprehension and then equal the data to your data frame. Please try the below code:
import pandas as pd
import math
d = {'label': [1, 2, 3, 4, 5], 'area': [1011, 107, 8, 18, 110],
'equivalent_diameter': [35.878199, 11.672045, 3.191538, 4.787307, 11.834541],
'mean_intensity': [255.0, 255.0, 76.0, 255.0, 255.0],
'solidity': [0.863365, 0.849206, 0.800000, 0.720000, 0.769231]}
df = pd.DataFrame(data=d)
data = df['area']/math.pi
df['area'] = [math.sqrt(i) for i in data]
print(df)