So given a cell I want to know the value in which the cell right before it (same row, previous column) has.
Here is my code and I thought it was working but...:
def excel_test(col_num, sheet_object):
for cell in sheet_object.columns[col_number]:
prev_col = (column_index_from_string(cell.column))
row = cell.row
prev_cell = sheet_object.cell(row, prev_col)
I keep getting this error:
coordinate = coordinate.upper().replace('$', '')
builtins.AttributeError: 'int' object has no attribute 'upper'
I have also tried this:
def excel_test(col_num, sheet_object):
for cell in sheet_object.columns[col_number]:
prev_col = (column_index_from_string(cell.column))
row = cell.row
prev_cell = sheet_object.cell(row, get_column_letter(prev_col))
Can somebody tell me how i can access that, I've also imported everything there needs to be imported.
You should look at the cell.offset() method.
Related
I find the required cell through the row number and column name (Column Search is necessary because columns can change their place in the table) and try to update its value using gspread. The code works without error, but for some reason it updates a completely different cell (A1)
import gspread
sa = gspread.service_account('path to service_account.json')
sh = sa.open('name of sheet')
wks = sh.worksheet('Sheet 1')
all = wks.get_all_records() #Get a list of dictionaries from the sheet
tab = 'Column number 3' #We will search and change the value from this column
cell_to_update = (all[0].get(tab)) #If we print() this, we get value of cell C2
wks.update(cell_to_update,'any text')
I do not know why, but it updates cell A1, although it should update cell C2
Thanks to a tip from #BRemmelzwaal, I found the answer to my question:
all = wks.get_all_records() #Get a list of dictionaries from the sheet
tab = 'Column number 3' #We will search and change the value from this column
value_to_update = (all[0].get(tab)) #If we print() this, we get value of cell C2
cell_to_update = wks.find(str(value_to_update))
wks.update_cell(cell_to_update.row, cell_to_update.col, 'any text')
Why am I getting this error if the column name exists.
I have tried everything. I am out of ideas
Since the AttributeError is raised at the first column with a name containing a mathematical symbol (µ), I would suggest you these two solutions :
Use replace right before the loop to get rid of this special character
df.columns = df.columns.str.replace("_\wg_", "_ug_", regex=True)
#change df to Table_1_1a_Tarawa_Terrace_System_1975_to_1985
Then inside the loop, use row.Mean_ug_L, .. instead of row.Mean_µg_L, ..
Use row["col_name"] (highly recommended) to refer to the column rather than row.col_name
for index, row in Table_1_1a_Tarawa_Terrace_System_1975_to_1985.iterrows():
SQL_VALUES_Tarawa = (row["Chemicals"], rows["Contamminant"], row["Mean_µg_L"], row["Median_µg_L"], row["Range_µg_L"], row["Num_Months_Greater_MCL"], row["Num_Months_Greater_100_µg_L"])
cursor.execute(SQL_insert_Tarawa, SQL_VALUES_Tarawa)
counting = cursor.rowcount
print(counting, "Record added")
conn.commit()
I am currently working on finding position(row index, column index) of maximum cell in each column of a dataframe.
There are a lot of similar dataframe like this, so I made a function like below.
def FindPosition_max(series_max, txt_name):
# series_max : only needed to get the number of columns in time_history(Index starts from 1).
time_history = pd.read_csv(txt_name, skiprows=len(series_max)+7, header=None, usecols=[i for i in range(1,len(series_max)+1)])[:-2]
col_index = series_max.index
row_index = []
for current_col_index in series_max.index:
row_index.append(time_history.loc[:, current_col_index].idxmax())
return row_index, col_index.tolist()
This works well, but takes too much time to run with a lot of dataframes. I found on the internet that .apply() is much more faster than for loop and I tried like this.
def FindPosition_max(series_max, txt_name):
time_history = pd.read_csv(txt_name, skiprows=len(series_max)+7, header=None, usecols=[i for i in range(1,len(series_max)+1)])[:-2]
col_index = series_max.index
row_index = pd.Series(series_max.index).apply(lambda x: time_history.loc[:, x].idxmax())
return row_index, series_max.index.tolist()
And the error comes like this,
File "C:\Users\hwlee\anaconda3\lib\site-packages\pandas\core\internals\construction.py", line 844, in _list_of_series_to_arrays
indexer = indexer_cache[id(index)] = index.get_indexer(columns)
AttributeError: 'builtin_function_or_method' object has no attribute 'get_indexer'
I tried to find what causes this error, but this error never goes away. Also when I tested the codes inside the function separately, it works well.
Could anyone help me to solve this problem? Thank u!
I really hope you can help.
I am working on the below, which finds the closest schools to a particular property.
Everything is working fine, except the final step. Where I define the field 'Primary' in the raw_data dataframe, it always returns NaN, but, if I step through, the variable Primary_Name does get populated.
Any idea why this might be?
for index, row in raw_data.iterrows():
start = (row['lat'], row['long'])
for index, row in schools.iterrows():
schoolloc = (row['Latitude'], row['Longitude'])
schools.loc[index,'distance'] = geopy.distance.geodesic(start, schoolloc).km
schools.dropna()
primary = schools.where(schools['PhaseOfEducation (name)'] == 'Primary')
Nearest_Primary = primary[primary['distance'] == min(primary['distance'])]
Primary_Name = Nearest_Primary.iloc[0]['EstablishmentName']
raw_data.loc[index,'primary'] = Primary_Name
I'm not able to set the header of a new column created in a table view.
This is the code:
def addColumn(self):
if self.tableView.selectionModel().hasSelection():
indexes = self.tableView.selectionModel().selectedColumns()
for index in sorted(indexes):
print('Adding column %d...' % index.column())
self.QSModel.insertColumn(index.column()+1)
self.QSModel.setHorizontalHeaderItem(index.column()+1,'XXX')
else:
print('No col selected!')
The error I get is:
self.QSModel.setHorizontalHeaderItem(index.column()+1,'XXX')
TypeError: setHorizontalHeaderItem(self, int, QStandardItem): argument 2 has unexpected type 'str'
How can I solve it?
As the error and the docs point out, the second parameter that is expected is a QStandardItem, not a string, in your case it should be:
self.QSModel.setHorizontalHeaderItem(index.column() + 1, QStandardItem('XXX'))