Python Undefined variable 'rg' [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to run this code, but get an error "name 'rg' is not defined". Could you please tell which library I can import rg from?
import numpy as np
a = np.floor(10*rg.random((3,4)))
print(a)
print(a.shape)

import numpy as np
rg = np.random.default_rng(1)
a = np.floor(10*rg.random((3,4)))
print(a)
print(a.shape)

If you wanted the rg.random() to give a random integer between two numbers, you would use random.randint(num1, num2).
So in your case, you would use this:
import numpy as np
import random
a = np.floor(10*random.randint((3,4)))
print(a)
print(a.shape)

import numpy as np
a = np.floor(10*np.random.rand((3,4)))
print(a)
print(a.shape)
np is the alias you are assigning to numpy, not ng

Related

Numpy producing different random numbers despite seed [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I had a problem with NumPy producing different random numbers despite seeding.
code:
import numpy as np
import random
random.seed(1234)
vec = np.random.normal(0, 1, size=6)
print(vec)
As I had set the seed, I expected vec to contain the same random numbers in every run.
But what I got:
run: vec = [-0.80715758 0.8377004 -0.98711439 -0.23424405 -1.85368722 0.97827818]
run: vec = [-0.74409802 -0.85180205 0.84585489 -0.40506222 -1.31125093 -1.23055255]
run: vec = [ 2.21521007 1.38577035 0.25437804 0.84529466 -0.83334042 1.00452671]
I was just posting this question when I found the solution.
But to prevent others from doing the same mistake, I thought it might be a good idea to post it anyway.
My mistake was the following:
I set the seed of random, not of np.random!
When setting the seed of the NumPy random number generator, everything works as expected:
import numpy as np
np.random.seed(1234)
vec = np.random.normal(0, 1, size=6)
vec will always contain the same random numbers.

pandas pivot multiple values for index [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am new to pandas and I have been struggling how to use pivot function.
I am trying to make the index as flat_type.
When I tried to use the pivot function, I kept getting this error:
TypeError: pivot() got multiple values for argument 'index'
And I have no idea how to fix it.
Any help or suggesttion would do greatly.! thankyou have a nice day!
link to dataset: https://data.gov.sg/dataset/median-rent-by-town-and-flat-type
code:
import pandas as pd
import numpy as np
df = pd.read_csv('median-rent-by-town-and-flat-type (1).csv',na_values=['na','-'])
mydf = df.dropna()
mydf = mydf.reset_index()
mydf.pivot(mydf,index="flat_type",columns="town",values="median_rent")
Remove mydf from pivot in paratheses, because already chained mydf with DataFrame.pivot method:
mydf.pivot(index="flat_type",columns="town",values="median_rent")
Another solution is use pandas.pivot - then is changed mydf.pivot to pd.pivot:
pd.pivot(mydf, index="flat_type",columns="town",values="median_rent")
Try my removing df
mydf.pivot(index="flat_type", columns="town", values="median_rent")
Thank you.

only length-1 arrays can be converted to Python scalars When using matlab keys [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm trying to convert serial date number data in a matlab file to UTC using python.
from datetime import *
import scipy.io as sio
import toutc as toutc
from numpy import *
from plotting import *
import matplotlib.pyplot as plt
S = sio.loadmat(*MatLab_File.mat*)
print (S.keys()) # Time is stored as the key 't'
from datetime import datetime, timedelta
SDN = S[str(input('time'))] # Establishing we are using the key 't'
X = (datetime.fromordinal(SDN) + timedelta(days=SDN%1) - timedelta(days = 366))
This last line returns
Traceback (most recent call last):
File "matgraph.py", line 19, in <module>
X = (datetime.fromordinal(SDN) + timedelta(days=SDN%1) - timedelta(days = >366))
TypeError: only length-1 arrays can be converted to Python scalars
Any idea why this isn't working?
Thank you
Edit: changed '[]' to '()' on last line and updated error to match
You have fromordinal[SDN] instead of fromordinal(SDN).
The error happens because you are trying to access a function as if it was an array. Remember that square brackets are for accessing values inside an array [], while parenthesis are for functions () in python.
datetime.fromordinal[SDN] should be datetime.fromordinal(SDN)

does python find errors where there are none? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
while plotting functions with heaviside function I came up with this piece of code, in Idle:
import numpy as np
import matplotlib.pyplot as plt
n_i = [-5, 5]
n = np.linspace(n_i[0], n_i[1], 1E3)
u1 [n+30>=0] = 1
u2 [n-15>=0] =1
u3 = u1 - u2
x = np.sin(2*np.pi*(n/15))*u3
plt.axis([-30,15,-5,5])
plt.xlabel('$n$',fontsize=20)
plt.ylabel('$x(n)$',fontsize=20)
plt.stem(n, x, "--k", linefmt='black', basefmt='black')
plt.grid()
plt.show()
and prior to today, it ran without errors, same with all other of my plots, I've been dealing with python for two years now and throughout classes it had the habit of finding errors where even teachers don't see them. am I missing something here? it says "u1 is not defined", but it is. I even compared with coworkers and classmates alike, haven't seen it put in any other way in the code for the plot. help!
You try to assign a value to u1[...] without even having created u1.
You should init u1 before trying to init its elements.

Plotting a complex function [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have a complex function to plot using Python, and then I have to find its root using ridder's method.
This is what I've done so far with my code but I keep running into a syntax error on a simple part of my code and have tried loads of things but nothing has given me a different result.
import math as m
from math import log
import numpy as np
import matplotlib.pyplot as plt
t = arange(0,250,0.1)
M = 2.8*10**6
n = 13.3*10**3
g = 9.8
u = 2510
plt.plot(u*(np.log((M)/(M-(n*t)))-g*t, t, 'r-^')
plt.xlabel('time')
plt.ylabel('velocity')
plt.show
Im being told my line where I am doing plt.xlabel has a syntax error and I can only assume the next line will do the same and I am not sure why.
Can someone point out my mistake please ?
first of all, arange belongs to numpy so you have to use np.arange
second, check parenthesis!
import math as m
from math import log
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0,250,0.1) #first line changed
M = 2.8*10**6
n = 13.3*10**3
g = 9.8
u = 2510
plt.plot(u*(np.log((M)/(M-(n*t))))-g*t, t, 'r-^') #second line changed
plt.xlabel('time')
plt.ylabel('velocity')
plt.show
here what I got!:

Categories