Dataframe not storing values - python

Pack_Perc = [[0]*4]*5
Pack_Dist = pd.DataFrame(Pack_Perc)
for i in range(4):
Pack_Dist.iloc[0][i] = my_data.iloc[i+1][9]
Pack_Dist.iloc[1][i] = my_data.iloc[i+1][11]
Pack_Dist.iloc[2][i] = my_data.iloc[i+1][13]
Pack_Dist.iloc[3][i] = my_data.iloc[i+1][15]
Pack_Dist.iloc[4][i] = my_data.iloc[i+1][17]
print(Pack_Dist)
I am trying to run above code & when I'm printing "Pack_Dist" instead of printing newly assigned values, system prints all 0s(the old values). Please provide any solution.

You should have provided my_data; but the only explanation is that value of those indices in my_data are zero.

Related

Writing to databases on Python

I have been trying to write to a database and am having trouble setting data using two different classes in the one function.
Firstly, all values are being passed through a GUI and in this case, only the following entries were passed: 'Categories' = C, 'Usage' = Charter, 'DispTHR' = 5000.
Here you can see that I have two classes I am wanting to access (airport and runway) where the function set_opsdatabase_details() will go to the appropriate class and write to our database. This is all well and good when the airport and runway are separate from each other; however, when integrating them in the same function I can't seem to get the corresponding airportvalueDict = {} and runwayvalueDict = {] to display the values I want. Could someone help me understand how to write the correct entry box values into the corresponding valueDict dictionaries?
Thank you in advance! (a screenshot of the output from the print statements is attached)
Function in python
Output of function with the print statements
Example of code in text format:
#edit function for first part of operational window
def edit_details1(self):
airport = self.manager.get_chosen_airport()
runway = airport.get_chosen_runway()
airportlabels = ['Category', 'Usage', 'Curfew',
'Surveyor', 'LatestSurvey',
'FuelAvail', 'FuelPrice', 'TankerPort', 'RFF']
runwaylabels = ['DispTHR', 'VASI', 'TCH']
airportvalueDict = {}
runwayvalueDict = {}
print(self.entryDict['Category']["state"])
if self.entryDict['Category']["state"] == 'disabled':
for entry in self.entryDict.values():
entry.config(state=tk.NORMAL)
self.editButton.config(text="Confirm")
elif self.entryDict['Category']['state'] == 'normal':
airport = self.manager.get_chosen_airport()
runway = airport.get_chosen_runway()
values = [x.get() for x in self.varDict.values()]
for label, value in zip(airportlabels, values):
airportvalueDict[label] = value
airport.set_opsdatabase_details(airportvalueDict)
print(f'airport: {airportvalueDict}')
for label, value in zip(runwaylabels, values):
runwayvalueDict[label] = value
runway.set_opsdatabase_details(runwayvalueDict)
print(f'runway: {runwayvalueDict}')
for entry in self.entryDict.values():
entry.config(state=tk.DISABLED)
self.editButton.config(text="Edit...")

Convert Data From One Type to Another ; astype/lstrip method in Python

I am trying to remove the '$' symbol in the 'salary' column. But its not working. What am I doing wrong? Ive tried many ways as seen below, but none of them are working. My dataframe is called "json".
json['salary'] = json['salary'].str.lstrip('$').astype(float)
minimal_salary = json['salary'] = json['salary'].str.replace('$','')
minimal_salary = json['salary'] = json['salary'].str.lstrip('$').astype('float')
json['minimal_salary'] = json['salary'].str.replace('$', '').str[:3].str.replace('K', '').str.strip().astype('float')
json['maximal_salary'] = json['salary'].str[6:10].str.replace('K','').str.lstrip('$').str.strip().astype('float')
json['average_salary'] = (json['minimal_salary'] + json['maximal_salary']) / 2
This should work and returns the resulting DataFrame directly.
json.assign(Salary=lambda d: d["Salary"].replace("$", "").astype("float"))
Alternatively, you can do it the "regular" way.
json["Salary"] = json["Salary"].replace("$", "").astype("float")

Change of variable values in Python without explicit changing them

I have the following code:
U_abs = abs(U)
index_max = np.argmax(U_abs[k:n,k])
memory_1 = U[k:n,k]
memory_2 = U[k:n,indice_max]
print(memory_1)
print(memory_2)
U[k:n,k] = memory_2
U[k:n,indice_max]= memory_1
print(memory_1)
print(memory_2)
I need the values of memory_1 and memory_2 not to change, but when I change the values of U[k:n,k] and U[k:n,index_max] the values of memory_1 and memory_2 change. This is my first day in Python. Any idea in how to fix this?
I'm assuming that everything you're doing here is using NumPy. If so, you can replace lines 3 and 4 with the copy operator:
memory_1 = U[k:n,k].copy()
memory_2 = U[k:n,indice_max].copy()

Create arrays of fixed size within a while loop in python

I am trying to create arrays of fixed size within a while loop. Since I do not know how many arrays I have to create, I am using a loop to initiate them within a while loop. The problem I am facing is, with the array declaration.I would like the name of each array to end with the index of the while loop, so it will be later useful for my calculations. I do not expect to find a easy way out, however it would be great if someone can point me in the right direction
I tried using arrayname + str(i). This returns the error 'Can't assign to operator'.
#parse through the Load vector sheet to load the values of the stress vector into the dataframe
Loadvector = x2.parse('Load_vector')
Lvec_rows = len(Loadvector.index)
Lvec_cols = len(Loadvector.columns)
i = 0
while i < Lvec_cols:
y_values + str(i) = np.zeros(Lvec_rows)
i = i +1
I expect arrays with names arrayname1, arrayname2 ... to be created.
I think the title is somewhat misleading.
An easy way to do this would be using a dictionary:
dict_of_array = {}
i = 0
while i < Lvec_cols:
dict_of_array[y_values + str(i)] = np.zeros(Lvec_rows)
i = i +1
and you can access arrayname1 by dict_of_array[arrayname1].
If you want to create a batch of arrays, try:
i = 0
while i < Lvec_cols:
exec('{}{} = np.zeros(Lvec_rows)'.format(y_values, i))
i = i +1

attatching a value to an array with a datapanel "item" as index in Python

essentially I want to attach a value to an array, indexing at the same time with, as index, the name of the "item" of the data panel. when looking at the code
#Scoring1[item] = 10 - max(ticker_2,ticker_1)
Scoring1 = []
series = pd.Panel.fromDict(series_col)
for item in series:
# f_cls = mp_thr[row["cls"]]
# thresholdSTABILE = mp_thr[cls][0]
thresholdSTABILE = 0.01
for j, p in enumerate(PercentiliUp):
if np.nanmean(series[item]['Ret']) + thresholdSTABILE > np.nanpercentile(series[item]['Ret'], p):
ticker_1=j
for j, p in enumerate(PercentiliDown):
if np.nanmean(series[item]['Ret']) - thresholdSTABILE < np.nanpercentile(series[item] ['Ret'], p):
ticker_2=j
#Scoring1[item] = 10 - max(ticker_2,ticker_1)
nothing seems to work. i get the:
TypeError: list indices must be integers or slices, not str
which I kind of get since I'd like to turn the "item" in a string as index, but I have been unable to do so.
in the hope that I could explain myself, any help is appreciated
sorry to have bothered you but I asked due to time sensitive constraints on a project. I found the solution, I just turned Scoring1 into a dictionary

Categories

Resources