AttributeError: 'function' object has no attribute 'values' heatmap - python

I'm trying to plot a heatmap using this code:
import folium
from folium.plugins import HeatMap
max_Count = (dataM['count'].max())
hmap = folium.Map(location=[53.192838, 8.197006], zoom_start=7,)
hm_wide = HeatMap( list(zip(dataM.latitude.values, dataM.longitude.values, dataM.count.values)),
min_opacity=0.2,
max_val=max_Count,
radius=17, blur=15,
max_zoom=1,
)
hmap.add_child(hm_wide)
the dataframe looks like that:
station count latitude longitude city
Time
2021-05-01 00:00:00 02-MI-JAN-N 11.0 52.5139 13.41780 Berlin
2021-05-01 00:00:00 24-MH-ALB 0.0 52.4925 13.55850 Berlin
2021-05-01 00:00:00 23-TK-KAI 1.0 52.4573 13.51870 Berlin
... ... ... ... ... ...
2021-09-09 23:45:00 50801_Amalienstr 0.0 53.1390 8.22225 Oldenburg
but i'm getting this error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-23-c1b7a410c325> in <module>
5 hmap = folium.Map(location=[53.192838, 8.197006], zoom_start=7,)
6
----> 7 hm_wide = HeatMap( list(zip(dataM.latitude.values, dataM.longitude.values, dataM.count.values)),
8 min_opacity=0.2,
9 max_val=max_Count,
AttributeError: 'function' object has no attribute 'values'
Any idea about the reason behind it and how can it be solved?
Thank you
UPDATE:
I've used dataM['latitude'], dataM['longitude'], dataM['count'] and it works :))

import folium
from folium.plugins import HeatMap
max_Count = (dataM['count'].max())
hmap = folium.Map(location=[53.192838, 8.197006], zoom_start=7,)
hm_wide = HeatMap( list(zip(dataM['latitude'], dataM['longitude'], dataM['count'])),
min_opacity=0.2,
max_val=max_Count,
radius=17, blur=15,
max_zoom=1,
)
hmap.add_child(hm_wide)

Related

python not recognizing pandas_ta module

import requests
import pandas as pd
import pandas_ta as ta
def stochFourMonitor():
k_period = 14
d_period = 3
data = get_data('BTC-PERP',14400,1642935495,1643165895)
print(data)
data = data['result']
df = pd.DataFrame(data)
df['trailingHigh'] = df['high'].rolling(k_period).max()
df['trailingLow'] = df['low'].rolling(k_period).min()
df['%K'] = (df['close'] - df['trailingLow']) * 100 / (df['trailingHigh'] - df['trailingLow'])
df['%D'] = df['%K'].rolling(d_period).mean()
df.index.name = 'test'
df.set_index(pd.DatetimeIndex(df["startTime"]), inplace=True)
print(df)
df.drop(columns=['startTime'])
print(df)
df.ta.stoch(high='High', low='Low',close= 'Close', k=14, d=3, append=True)
#t = ta.stoch(close='close',high='high', low='low', k=14, d=3, append=True)
#df.ta.stoch(close='close',high='high', low='low', k=14, d=3, append=True)
def get_data(marketName,resolution,start_time,end_time):
data = requests.get('https://ftx.com/api/markets/' + marketName + '/candles?resolution=' + str(resolution) + '&start_time=' + str(start_time) + '&end_time=' + str(end_time)).json()
return data
I keep receiving the error 'NoneType' object has no attribute 'name'. See below for full exception. It seems like the code is not recognizing the pandas_ta module but I don't understand why. Any help troubleshooting would be much appreciated.
Exception has occurred: AttributeError (note: full exception trace is shown but execution is paused at: )
'NoneType' object has no attribute 'name'
File "C:\Users\Jason\Documents\TradingCode\FTX Websocket\testing21.py", line 21, in stochFourMonitor
df.ta.stoch(high='High', low='Low',close= 'Close', k=14, d=3, append=True)
File "C:\Users\Jason\Documents\TradingCode\FTX Websocket\testing21.py", line 31, in (Current frame)
stochFourMonitor()
You have to few values in your dataframe. You need at least 17 values (k=14, d=3)
>>> pd.Timestamp(1642935495, unit='s')
Timestamp('2022-01-23 10:58:15')
>>> pd.Timestamp(1643165895, unit='s')
Timestamp('2022-01-26 02:58:15')
>>> pd.DataFrame(get_data('BTC-PERP',14400,1642935495,1643165895)['result'])
0 2022-01-23T12:00:00+00:00 1.642939e+12 35690.0 36082.0 35000.0 35306.0 6.315513e+08
1 2022-01-23T16:00:00+00:00 1.642954e+12 35306.0 35460.0 34601.0 34785.0 7.246238e+08
2 2022-01-23T20:00:00+00:00 1.642968e+12 34785.0 36551.0 34712.0 36271.0 9.663773e+08
3 2022-01-24T00:00:00+00:00 1.642982e+12 36271.0 36283.0 35148.0 35351.0 6.007333e+08
4 2022-01-24T04:00:00+00:00 1.642997e+12 35351.0 35511.0 34821.0 34896.0 5.554126e+08
5 2022-01-24T08:00:00+00:00 1.643011e+12 34895.0 35610.0 33033.0 33709.0 1.676436e+09
6 2022-01-24T12:00:00+00:00 1.643026e+12 33709.0 34399.0 32837.0 34260.0 2.021096e+09
7 2022-01-24T16:00:00+00:00 1.643040e+12 34261.0 36493.0 33800.0 36101.0 1.989552e+09
8 2022-01-24T20:00:00+00:00 1.643054e+12 36101.0 37596.0 35990.0 36673.0 1.202684e+09
9 2022-01-25T00:00:00+00:00 1.643069e+12 36673.0 36702.0 35974.0 36431.0 4.538093e+08
10 2022-01-25T04:00:00+00:00 1.643083e+12 36431.0 36500.0 35719.0 36067.0 3.514587e+08
11 2022-01-25T08:00:00+00:00 1.643098e+12 36067.0 36824.0 36030.0 36431.0 5.830712e+08
12 2022-01-25T12:00:00+00:00 1.643112e+12 36431.0 37200.0 35997.0 36568.0 9.992247e+08
13 2022-01-25T16:00:00+00:00 1.643126e+12 36568.0 37600.0 36532.0 37079.0 8.225219e+08
14 2022-01-25T20:00:00+00:00 1.643141e+12 37077.0 37140.0 36437.0 36980.0 7.892745e+08
15 2022-01-26T00:00:00+00:00 1.643155e+12 36980.0 37242.0 36567.0 37238.0 3.226400e+08
>>> pd.DataFrame(get_data('BTC-PERP',14400,1642935495,1643165895)['result'])
...
AttributeError: 'NoneType' object has no attribute 'name'
Now change 1642935495 ('2022-01-23 10:58:15') by 1642845495 ('2022-01-22 10:58:15':
>>> pd.DataFrame(get_data('BTC-PERP',14400,1642845495,1643165895)['result']).ta.stoch()
STOCHk_14_3_3 STOCHd_14_3_3
13 NaN NaN
14 NaN NaN
15 80.824814 NaN
16 74.665546 NaN
17 72.970512 76.153624
18 73.930097 73.855385
19 80.993469 75.964693
20 84.814444 79.912670
21 89.775352 85.194422

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'

TypeError: unhashable type: 'numpy.ndarray

I keep getting TypeError: unhashable type: 'numpy.ndarray' when I run this code. I'm unable to pinpoint the issue.
When I do .head() this is what I get:
|Year|Chinese|Malay|Indian|Others|
|----+-------+-----+------+------|
|2010| 96| 87.9| 92| 87.7|
|2011| 96.3| 89.3| 92.5| 91.7|
|2012| 97.1| 91| 92.5| 92.6|
|2013| 97.2| 91.7| 92.3| 93.6|
|2014| 97.5| 93.5| 93.2| 93.5|
My code:
df_tertiary = pd.read_csv('percentage-of-p1-cohort-that-progressed-to-post-secondary-education.csv',index_col=0);
df_tertiary_chi = df_tertiary[df_tertiary.race == 'Chinese']
df_tertiary_malay = df_tertiary[df_tertiary.race == 'Malay']
df_tertiary_indian = df_tertiary[df_tertiary.race == 'Indian']
df_tertiary_others = df_tertiary[df_tertiary.race == 'Others']
df_tertiary_total = pd.concat([df_tertiary_chi['percentage_p1_cohort_post_sec'],df_tertiary_malay['percentage_p1_cohort_post_sec'],df_tertiary_indian['percentage_p1_cohort_post_sec'],df_tertiary_others['percentage_p1_cohort_post_sec']], axis=1, sort=False)
df_tertiary_total.columns = ['Chinese','Malay','Indian','Others']
df_tertiary_total = df_tertiary_total.loc['2010':'2019']
df_tertiary_total = pd.DataFrame(df_tertiary_total)
display(df_tertiary_total.head())
plt.plot(df_tertiary_total)
plt.show()
Error:
TypeError Traceback (most recent call last)
<ipython-input-200-1000efab126d> in <module>
14 display(df_tertiary_total.head())
15
---> 16 plt.plot(df_tertiary_total)
17 plt.show()
Data Sample
Chinese Malay Indian Others
year
2016 97.8 93.1 93.8 93.9

Update row after comparing values on pandas dataframe

I connect to an API that provides covid-19 data in Brazil organized by state and city, as follows:
#Bibliotecas
import pandas as pd
from pandas import Series, DataFrame, Panel
import matplotlib.pyplot as plt
from matplotlib.pyplot import plot_date, axis, show, gcf
import numpy as np
from urllib.request import Request, urlopen
import urllib
from http.cookiejar import CookieJar
import numpy as np
from datetime import datetime, timedelta
cj = CookieJar()
url_Bso = "https://brasil.io/api/dataset/covid19/caso_full/data?state=MG&city=Barroso"
req_Bso = urllib.request.Request(url_Bso, None, {"User-Agent": "python-urllib"})
opener_Bso = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
response_Bso = opener_Bso.open(req_Bso)
raw_response_Bso = response_Bso.read()
json_Bso = pd.read_json(raw_response_Bso)
results_Bso = json_Bso['results']
results_Bso = results_Bso.to_dict().values()
df_Bso = pd.DataFrame(results_Bso)
df_Bso.head(5)
This Api compiles the data released by the state health departments. However, there is a difference between the records of the state and city health departments, and the state records are out of date in relation to those of the cities. I would like to update Thursdays and Saturdays (the day when the epidemiological week ends). I'm trying the following:
saturday = datetime.today() + timedelta(days=-5)
yesterday = datetime.today() + timedelta(days=-1)
last_available_confirmed_day_Bso_saturday = 51
last_available_confirmed_day_Bso_yesterday = 54
df_Bso = df_Bso.loc[df_Bso['date'] == saturday, ['last_available_confirmed']] = last_available_confirmed_day_Bso_saturday
df_Bso = df_Bso.loc[df_Bso['date'] == yesterday, ['last_available_confirmed']] = last_available_confirmed_day_Bso_yesterday
df_Bso
However, I get the error:
> AttributeError: 'int' object has no attribute 'loc'
I need another dataframe with the values of these days updates. Can anyone help?
You have to adjust the date. Your data frame date column is a string. You can convert them to datetime.
today = datetime.now()
last_sat_num = (today.weekday() + 2) % 7
last_thu_num = (today.weekday() + 4) % 7
last_sat = today - timedelta(last_sat_num)
last_thu = today - timedelta(last_thu_num)
last_sat_str = last_sat.strftime('%Y-%m-%d')
last_thu_str = last_thu.strftime('%Y-%m-%d')
last_available_confirmed_day_Bso_sat = 51
last_available_confirmed_day_Bso_thu = 54
df_Bso2 = df_Bso.copy()
df_Bso2.loc[df_Bso2['date'] == last_sat_str, ['last_available_confirmed']] = last_available_confirmed_day_Bso_sat
df_Bso2.loc[df_Bso2['date'] == last_thu_str, ['last_available_confirmed']] = last_available_confirmed_day_Bso_thu
df_Bso2[['date', 'last_available_confirmed']].head(10)
Output
date last_available_confirmed
0 2020-07-15 44
1 2020-07-14 43
2 2020-07-13 40
3 2020-07-12 40
4 2020-07-11 51
5 2020-07-10 39
6 2020-07-09 36
7 2020-07-08 36
8 2020-07-07 27
9 2020-07-06 27

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