sqrt and float data in python [duplicate] - python

This question already has answers here:
Change type of pandas series/dataframe column inplace
(4 answers)
Closed 1 year ago.
I have some problem in my code
its result error "AttributeError: 'Series' object has no attribute 'float'"
i need solution to solve it
my code
def calculateED (pdX, pdY):
arg = (((pdX['NormalTemp']-pdY[0])**2)+
((pdX['NormalHumidity']-pdY[1])**2)+
((pdX['NormalOutlook']-pdY[2])**2)+
((pdX['NormalWindy']-pdY[3])**2)).float()
pdX['ED']= math.sqrt(arg1)
return pdX
dataTest = [64.0,65.0,1.0,1.0]
ngitung = calculateED(dataset, dataTest)
ngitung.sort_values(by=['ED'])
but after run this code i have some problem
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-21-034dd0366562> in <module>
1 dataTest = (64.0,65.0,1.0,1.0)
2 #dataTest2 = [72.0,95.0,3.0,0.0]
----> 3 ngitung = calculateED(dataset, dataTest)
4 #ngitung2 = calculateED2(dataset, dataTest2)
5 ngitung.sort_values(by=['ED'])
<ipython-input-15-5ae8a365490e> in calculateED(pdX, pdY)
1 def calculateED (pdX, pdY):
----> 2 arg = (((pdX['NormalTemp']-pdY[0])**2)+
3 ((pdX['NormalHumidity']-pdY[1])**2)+
4 ((pdX['NormalOutlook']-pdY[2])**2)+
5 ((pdX['NormalWindy']-pdY[3])**2)).float()
c:\users\windows\appdata\local\programs\python\python39\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
5463 if self._info_axis._can_hold_identifiers_and_holds_name(name):
5464 return self[name]
-> 5465 return object.__getattribute__(self, name)
5466
5467 def __setattr__(self, name: str, value) -> None:
AttributeError: 'Series' object has no attribute 'float'

According to this topic:
numpy functions require float type argument explicity
Example:
import numpy as np
your_array = your_array.float()
output = np.exp(your_array)
In your case:
def calculateED (pdX, pdY):
argument = ((pdX['NormalTemp']-pdY[0])**2)+
((pdX['NormalHumidity']-pdY[1])**2)+
((pdX['NormalOutlook']-pdY[2])**2)+
((pdX['NormalWindy']-pdY[3])**2).float()
pdX['ED']= np.sqrt(argument)
return pdX

Related

Apply a binomial function to every row in a pandas Dataframe

I am using the following code on that dataframe:
Here picture of the dataframe used
not_rescued = df["not_rescued"]
rescued = df["rescued"]
breed = df["breed"]
def get_attribute(breed, attribute):
if breed in df.breed.unique():
if attribute in df.columns:
return df[df["breed"] == breed][attribute]
else:
raise NameError('Attribute {} does not exist.'.format(attribute))
else:
raise NameError('Breed {} does not exist.'.format(breed))
def get_not_rescued(breed):
return get_attribute(breed, 'not_rescued')
def get_rescued(breed):
return get_attribute(breed, 'rescued')
def get_total(breed):
return get_attribute(breed, 'total')
from scipy.stats import binom_test
binomial_test = binom_test(get_rescued(breed), get_total(breed), 0.08)
print(binomial_test)
I would like to apply the binomial function without having to call the function each time for each dog.. How could I use a list without having the following error:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [18], in <cell line: 2>()
1 from scipy.stats import binom_test
----> 2 binomial_test = binom_test(get_rescued(breed), get_total(breed), 0.08)
3 print(binomial_test)
File ~/opt/anaconda3/lib/python3.9/site-packages/scipy/stats/morestats.py:2667, in binom_test(x, n, p, alternative)
2665 n = np.int_(n)
2666 else:
-> 2667 raise ValueError("Incorrect length for x.")
2669 if (p > 1.0) or (p < 0.0):
2670 raise ValueError("p must be in range [0,1]")
ValueError: Incorrect length for x.

Getting "AttributeError: 'numpy.ndarray' object has no attribute 'transform'" from esda.Moran

Trying to get Moran's I. A test but getting "AttributeError: 'numpy.ndarray' object has no attribute 'transform'" because of the last line of code. Both of the variables are arrays and they look like this:
0 1024.798431
1 859.662720
2 870.632530
3 819.316065
4 930.600992
...
5567 842.415062
5568 991.513211
5569 908.701993
5570 909.431369
5571 644.946254
Name: Auxilio, Length: 5572, dtype: float64
peso_espacial:
array([876.56886196, 815.34772578, 871.227145 , ..., 903.74618016,
880.30363602, 885.61222452])
And the code is this:
mun = geobr.read_municipality(code_muni="all", year=2019)
mun = mun.rename(columns={'code_muni': 'Municipio'})
mun['Municipio'] = mun['Municipio'].astype(int).astype(str).str[:-1].astype(np.int64)
impacto2020 = pd.read_excel(path)
mapa = pd.merge(mun,impacto2020,on='Municipio',how='left')
qW = ps.lib.weights.Queen.from_dataframe(mapa)
qW.transform = 'r'
peso_espacial = lp.weights.lag_spatial(qW, mapa['Auxilio'])
peso_espacial = np.nan_to_num(peso_espacial)
auxilio = mapa['Auxilio']
from esda.moran import Moran
moran = Moran(auxilio, peso_espacial)
Don't know how to fix it, already tried converting it to a Series but it gets pretty much the same AttributeError. And this should return a number between 0 and 1.
Full error traceback:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-63-e8e3103abd6b> in <module>
1 from esda.moran import Moran
----> 2 moran = Moran(auxilio, peso_espacial)
/opt/anaconda3/lib/python3.8/site-packages/esda/moran.py in __init__(self, y, w, transformation, permutations, two_tailed)
159 y = np.asarray(y).flatten()
160 self.y = y
--> 161 w.transform = transformation
162 self.w = w
163 self.permutations = permutations
AttributeError: 'numpy.ndarray' object has no attribute 'transform'

Get values from a dict in an column. AttributeError: 'NoneType' object has no attribute 'get' when a value is "None"

I have this df
simbolo puntas ultimoPrecio
10 AE38 {'cantidadCompra': 79668.0, 'precioCompra': 60... 6080.00
11 AL41C None 36.50
and I get the first value from dict in "puntas" column.
p['Cant_Compra']=[x.get('cantidadCompra',0) for x in p['puntas']]
output:
simbolo Cant_Compra ultimoPrecio
10 AE38 79668.0 6080.00
but if value is None as line 11 appears next error message:
AttributeError: 'NoneType' object has no attribute 'get'
what can I do?
this works :
def fun(x):
if x==None:
return None
return x['cantidadCompra']
p['Cant_Compra']=p['puntas'].apply(func=fun)
import ast
from io import StringIO
# sample data
s = """simbolo|puntas|ultimoPrecio
AE38|{'cantidadCompra': 79668.0, 'precioCompra': 60}|6080.00
AL41C|None|36.50"""
df = pd.read_csv(StringIO(s), sep='|')
df['puntas'] = df['puntas'].apply(ast.literal_eval)
# convert the dict column to a dataframe and assign the values to your column
df['Cant_Compra'] = pd.DataFrame(df['puntas'].to_dict()).T['cantidadCompra']
simbolo puntas ultimoPrecio \
0 AE38 {'cantidadCompra': 79668.0, 'precioCompra': 60} 6080.0
1 AL41C None 36.5
Cant_Compra
0 79668
1 None

Getting Attribute Error While Syncing Jupyter NB to Google Sheets

I am trying to integrate my Jupyter Notebook with Google Sheets. I am trying to execute below code and it is giving me attribute error. Need your help to solve the same.
# Set the sheet name you want to upload data to and the start cell where the upload data begins
wks_name = 'Sheet1'
cell_of_start_df = 'A2'
# upload the dataframe of the clients we want to delete
d2g.upload(rs,
spreadsheet_key,
wks_name,
credentials=credentials,
col_names=False,
row_names=False,
start_cell = cell_of_start_df,
clean=False)
print ('The sheet is updated successfully')
I am getting below error:
AttributeError Traceback (most recent call last)
<ipython-input-30-6aac4a76409f> in <module>
10 row_names=False,
11 start_cell = cell_of_start_df,
---> 12 clean=False)
13 print ('The sheet is updated successfully')
~\Anaconda3\lib\site-packages\df2gspread\df2gspread.py in upload(df, gfile, wks_name, col_names, row_names, clean, credentials, start_cell, df_size, new_sheet_dimensions)
99 last_idx = num_rows + last_idx_adjust
100
--> 101 num_cols = len(df.columns) + 1 if row_names else len(df.columns)
102 last_col_adjust = start_col_int - 1
103 last_col_int = num_cols + last_col_adjust
~\Anaconda3\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
5268 or name in self._accessors
5269 ):
-> 5270 return object.__getattribute__(self, name)
5271 else:
5272 if self._info_axis._can_hold_identifiers_and_holds_name(name):
AttributeError: 'Series' object has no attribute 'columns'
It will be of great help if it gets solved.
Additional Code:
cols = ['Cases']
mask = lk[cols].applymap(lambda x: isinstance(x, (int, float)))
lk[cols] = lk[cols].where(mask)
print (lk)
mn = lk.replace('NaN',0)
mn
rs=mn.groupby(['States and UTs','district','status'])[mn.columns[0]].sum()
rs

loop the pycountry convert

def country_to_continent(country_name):
country_alpha2 = pc.country_name_to_country_alpha2(country_name)
country_continent_code = pc.country_alpha2_to_continent_code(country_alpha2)
country_continent_name = pc.convert_continent_code_to_continent_name(country_continent_code)
return country_name
country_name = [i for i in df['country']]
country_to_continent(country_name)
this is my code and I want to loop my df['country'] and get the continent name but it has error TypeError: unhashable type: 'list'
my purpose is to convert a country to the continent and to calculate every sum of continent's suicides cases
This is my entire error message
TypeError Traceback (most recent call last)
<ipython-input-197-3be113b9bda3> in <module>
6
7 country_name = [i for i in df['country']]
----> 8 country_to_continent(country_name)
<ipython-input-197-3be113b9bda3> in country_to_continent(country_name)
1 def country_to_continent(country_name):
----> 2 country_alpha2 = pc.country_name_to_country_alpha2(country_name)
3 country_continent_code = pc.country_alpha2_to_continent_code(country_alpha2)
4 country_continent_name = pc.convert_continent_code_to_continent_name(country_continent_code)
5 return country_name
D:\pythin\lib\site-packages\pycountry_convert\convert_countries.py in country_name_to_country_alpha2(cn_name, cn_name_format)
68 return cn_name
69
---> 70 if cn_name not in dict_country_name_to_country_alpha2:
71 raise KeyError("Invalid Country Name: '{0}'".format(cn_name))
72
TypeError: unhashable type: 'list'

Categories

Resources