A type error: 'builtin_function_or_method' object does not support item assignment. How can I fix that? - typeerror

I'm running the following code and got a type error:
TypeError: 'builtin_function_or_method' object does not support item assignment
Here's my code:
N_object4 = 4
alpha = np.random.normal(0, 10, N_object4)# Random alpha values (could be greater or less than 0.)
pa = np.abs(alpha)
num = pa.argsort()[-3:][::-1]
gs = np.zeros(N_object4).tolist
for i in range (len(num)): # Iterating from largest abs(alpha) to the smallest.
if alpha[num[i]] > 0:
gs[num[i]+1] = 1
The error happens in my last line. How can I fix this error? Thanks!!

I think its small typo in line 4. You should use tolist():
gs = np.zeros(N_object4).tolist()

Related

TypeError: '<' not supported between instances of 'int' and 'Timestamp'

I am trying to change the product name when the period between the expiry date and today is less than 6 months. When I try to add the color, the following error appears:
TypeError: '<' not supported between instances of 'int' and 'Timestamp'.
Validade is the column where the products expiry dates are in. How do I solve it?
epi1 = pd.read_excel('/content/timadatepandasepi.xlsx')
epi2 = epi1.dropna(subset=['Validade'])`
pd.DatetimeIndex(epi2['Validade'])
today = pd.to_datetime('today').normalize()
epi2['ate_vencer'] = (epi2['Validade'] - today) /np.timedelta64(1, 'M')
def add_color(x):
if 0 <x< epi2['ate_vencer']:
color='red'
return f'background = {color}'
epi2.style.applymap(add_color, subset=['Validade'])
Looking at your data, it seems that you're subtracting two dates and using this result inside your comparison. The problem is likely occurring because df['date1'] - today returns a pandas.Series with values of type pandas._libs.tslibs.timedeltas.Timedelta, and this type of object does not allow you to make comparisons with integers. Here's a possible solution:
epi2['ate_vencer'] = (epi2['Validade'] - today).dt.days
# Now you can compare values from `"ate_vencer"` with integers. For example:
def f(x): # Dummy function for demonstration purposes
return 0 < x < 10
epi2['ate_vencer'].apply(f) # This works
Example 1
Here's a similar error to yours, when subtracting dates and calling function f without .dt.days:
Example 2
Here's the same code but instead using .dt.days:

Error while transforming series with series.map() function

def locate (code):
string1 = str(code)
floor = string1[3]
if floor == '1':
return 'Ground Floor'
else:
if int(string1[5]) < 1:
lobby = 'G'
elif int(string1[5]) < 2:
lobby = 'F'
else:
lobby = 'E'
return floor + lobby
print(locate('S191009'))
print(locate('S087525'))
This function works fine with individual input code as above with Output
Ground Floor
7E
But when I use this to map a series in data frame, it shows error.
error_data1['location'] = error_data1['status'].map(locate)
Error message: string index out of range.
How can I fix this??
Your problem is with your series values:
se = pd.Series(['S191009', 'rt'])
se.map(locate)
produces the same error you reported. You can ignore these rows using try...except in function if it does not hurt you.
The problem is you are indexing an index on a string that doesn't exist (i.e the string is shorter than what you expect). As the other answer mentioned, if you try and use
my_string="foo"
print(my_string[5])
You will get the same error. To solve this you should add a try except statement, or for simplicity an initial if statement that returns "NotValid" or something like that. Your data probably has strings that do not follow the standard form you expect.

Strange numbers in the output from Netcdf in Fortran

I'm fairly new to Fortran and try reading in 3D (80000*100*10) single precision NetCDF data (however I'd just read it 2D like (80000,100,1st)). I would need to convert them into double precision for some further code not shown below.
The .nc-File which I create to check if the reading/writing works does contain only "0" if I use real single precision for all NF90-functions as well as the variable 'values'.
It does contain mostly "0" and several weird numbers which don't seem to relate in a conceivable way to the input data if I use double precision (code shown below). At least I get any output in my nc file this way.
I don't get any compiling errors {nor error codes in 'STATUS' if I check for specific lines after NF90 functions. Update: That was mistaken}. Input_test.nc gets created exactly as expected regarding dimensions, but not regarding the actual values.
My code is:
PROGRAM read
Implicit None
INCLUDE 'netcdf.inc'
INTEGER :: NCID, horstart, verstart, horlen, verlen, horcount, vercount, STATUS, STATUS2
REAL(kind=8), DIMENSION(80000,100) :: values
horstart = 1
verstart = 1
horcount = 80000 !!(tried to use this instead of horlen, doesn't change anything)
vercount = 100 !!(tried to use this instead of verlen, doesn't change)
varname = 'pres'
!! get input data
STATUS = NF90_OPEN('my_valid_path/file.nc', 0, NCID)
STATUS = NF90_INQ_DIMID(NCID, 'ncells', horid)
STATUS = NF90_INQ_DIMID(NCID, 'height', verid)
STATUS = NF90_INQ_DIMLEN(NCID,horid,horlen)
STATUS = NF90_INQ_DIMLEN(NCID,verid,verlen)
STATUS = NF90_INQ_VARID(NCID,varname,varid)
STATUS = NF90_GET_VARA_DOUBLE(NCID,varid,[horstart,verstart,1],[horlen,verlen,1],values)
STATUS = NF90_CLOSE(NCID)
STATUS = NF90_CREATE ('some_path/input_test.nc', 0, ncid);
STATUS = NF90_DEF_DIM (ncid, 'hor',horcount, dimhor)
STATUS = NF90_DEF_DIM (ncid, 'ver',vercount, dimver)
STATUS = NF90_DEF_DIM (ncid, '1d',1, dimcode)
STATUS = NF90_DEF_VAR(ncid,'pres',NF90_DOUBLE,2,[dimhor,dimver],pres_id)
STATUS = NF90_DEF_VAR(ncid,'status',NF90_INT,1,dimcode,stat_id)
STATUS = NF90_ENDDEF(ncid)
STATUS = NF90_PUT_VARA_DOUBLE(ncid,pres_id,[horstart,verstart],[horcount,vercount],values)
STATUS = NF90_PUT_VARA_INT(ncid,stat_id,1,1,STATUS2)
STATUS = NF90_CLOSE(ncid)
The nc file I read from doesn't contain any zeroes, not even in the 3rd dimension. The Output file however does contain a lot zeroes, it is not empty though.
Example input: 0,095213220 0,099325478 0,10358732 0,10800611 0,11259078 0,11734842 0,12228279 0,12740466 0,13271827 0,13822863 0,14394356
Example output: 0 0 0 0 0 0,000493943283800036 0,000594558776356280 0,000234268474741839 2,88491937681101e-05 2,09666131608306e-16 7,30948746534081e-20
I'm probably doing something stupid, but I went temporarily out of ideas what to check for.
UPDATE: Thoroughly checking the error codes saved in STATUS did give a non-zero match at NF90_GET_VARA_DOUBLE/(also REAL). Getting back to this tomorrow.
With error handler I came to the conclusion that the above code works. The errors eventually came from a spelling mistake of the variables I tried to read from.

PuLP - COIN-CBC error: How to add constraint with double inequality and relaxation?

I want to add this set of constraints:
-M(1-X_(i,j,k,n) )≤S_(i,j,k,n)-ToD_(i,j,k,n)≤M(1-X_(i,j,k,n) ) ∀i,j,k,n
Where M is a big number, S is a integer variable that takes values between 0 and 1440. ToD is a 4-dimensional matrix that takes values from an Excel sheet. X i dual variable, it takes as values 0-1.
I try to implement in code as following:
for n in range(L):
for k in range(M):
for i in range(N):
for j in range(N):
if (i != START_POINT_S & i != END_POINT_T & j != START_POINT_S & j != END_POINT_T):
prob += (-BIG_NUMBER*(1-X[i][j][k][n])) <= (S[i][j][k][n] - ToD[i][j][k][n]), ""
and another constraint as follows:
for i in range(N):
for j in range(N):
for k in range(M):
for n in range(L):
if (i != START_POINT_S & i != END_POINT_T & j != START_POINT_S & j != END_POINT_T):
prob += S[i][j][k][n] - ToD[i][j][k][n] <= BIG_NUMBER*(1-X[i][j][k][n]), ""
According to my experience, in code, those two constraints are totally equivalent to what we want. The problem is that PuLP and CBC won't accept them. The produce the following errors:
PuLP:
Traceback (most recent call last):
File "basic_JP.py", line 163, in <module>
prob.solve()
File "C:\Users\dimri\Desktop\Filesystem\Projects\deliverable_B4\lib\site-packa
ges\pulp\pulp.py", line 1643, in solve
status = solver.actualSolve(self, **kwargs)
File "C:\Users\dimri\Desktop\Filesystem\Projects\deliverable_B4\lib\site-packa
ges\pulp\solvers.py", line 1303, in actualSolve
return self.solve_CBC(lp, **kwargs)
File "C:\Users\dimri\Desktop\Filesystem\Projects\deliverable_B4\lib\site-packa
ges\pulp\solvers.py", line 1366, in solve_CBC
raise PulpSolverError("Pulp: Error while executing "+self.path)
pulp.solvers.PulpSolverError: Pulp: Error while executing C:\Users\dimri\Desktop
\Filesystem\Projects\deliverable_B4\lib\site-packages\pulp\solverdir\cbc\win\64\
cbc.exe
and CBC:
Welcome to the CBC MILP Solver
Version: 2.9.0
Build Date: Feb 12 2015
command line - C:\Users\dimri\Desktop\Filesystem\Projects\deliverable_B4\lib\sit
e-packages\pulp\solverdir\cbc\win\64\cbc.exe 5284-pulp.mps branch printingOption
s all solution 5284-pulp.sol (default strategy 1)
At line 2 NAME MODEL
At line 3 ROWS
At line 2055 COLUMNS
Duplicate row C0000019 at line 10707 < X0001454 C0000019 -1.000000000000e+
00 >
Duplicate row C0002049 at line 10708 < X0001454 C0002049 -1.000000000000e+
00 >
Duplicate row C0000009 at line 10709 < X0001454 C0000009 1.000000000000e+
00 >
Duplicate row C0001005 at line 10710 < X0001454 C0001005 1.000000000000e+
00 >
At line 14153 RHS
At line 16204 BOUNDS
Bad image at line 17659 < UP BND X0001454 1.440000000000e+03 >
At line 18231 ENDATA
Problem MODEL has 2050 rows, 2025 columns and 5968 elements
Coin0008I MODEL read with 5 errors
There were 5 errors on input
** Current model not valid
Option for printingOptions changed from normal to all
** Current model not valid
No match for 5284-pulp.sol - ? for list of commands
Total time (CPU seconds): 0.02 (Wallclock seconds): 0.02
I don't know what's the problem, any help? I am new to this, if information are not enough let me know what I should add.
Alright, I have searched for hours, but right after I posted this question I found the answer. These kinds of problems are mainly because of the names of the variables or the constraints. That is what caused something to duplicate. I am really not used to that kind of software that is why it took me so long to find and answer. Anyway, the problem for me was when I was defining the variables:
# define X[i,j,k,n]
lower_bound_X = 0 # lower bound for variable X
upper_bound_X = 1 # upper bound for variable X
X = LpVariable.dicts(name="X",
indexs=(range(N), range(N), range(M), range(L)),
lowBound=lower_bound_X,
upBound=upper_bound_X,
cat=LpInteger)
and
# define S[i,j,k,n]
lower_bound_S = 0 # lower bound for variable S
upper_bound_S = 1440 # upper bound for variable S
S = LpVariable.dicts(name="X",
indexs=(range(N),
range(N), range(M), range(L)),
lowBound=lower_bound_S,
upBound=upper_bound_S,
cat=LpInteger)
As you see in the definition of S I obviously forgot to change the name of the variable to S because I copy-pasted it. Anyway, the right way to define S is like this:
# define S[i,j,k,n]
lower_bound_S = 0 # lower bound for variable S
upper_bound_S = 1440 # upper bound for variable S
S = LpVariable.dicts(name="S",
indexs=(range(N), range(N), range(M), range(L)),
lowBound=lower_bound_S,
upBound=upper_bound_S,
cat=LpInteger)
This is how I got my code running.

SQL function with square roots causes problems

I have a query that is erroring out:
SET #SumDiff = #SitesSum - (select power(SUM(Sums),2)/#NumSites from #SiteSums)
SET #SE = power((#SumDiff/(#NumSites - 1)),0.5)/power(#NumSites,0.5)
This function works most of the time, but I get an error some times.
Here are the values when i have the problem.
SUM(Sums) = .01 so squared = .001
#NumSites = 2
#SiteSum = 0
The value from this part:
select power(#Sums,2)/#NumSites from #SiteSums
comes out as 5E-05 which would match the value expected, .00005
When I try to set #SE it's basically finding the square root of (.00005 / 1)/ square root of 2 (1.4142135623731).
Should be something like 3.535533905932725. But I get the message:
Msg 3623, Level 16, State 1, Line 306
An invalid floating point operation occurred.
Is .00005 too small to divide in SQL? Could I do a cast? This isn't always going to be working with decimals, mostly larger numbers.
Actually, using your values this:
SET #SumDiff = #SitesSum - (select power(SUM(Sums),2)/#NumSites from #SiteSums)
..results in #SumDiff being set to -5E-05, and not 5E-05.
So when you then do:
power((#SumDiff/(#NumSites - 1)),0.5)
..you are trying to take the square root of a negative number which is invalid (undefined) for a Real number.
The ABS(..) function can fix this for you:
SET #SE = power((ABS(#SumDiff)/(#NumSites - 1)),0.5)/power(#NumSites,0.5)