Setting a column header in a table model - python

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'))

Related

AttributeError: 'Series' object has no attribute 'Mean_μg_L'

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()

Timestamp object has no attribute dt

I am trying to convert a new column in a dataframe through a function based on the values in the date column, but get an error indicating "Timestamp object has no attribute dt." However, if I run this outside of a function, the dt attribute works fine.
Any guidance would be appreciated.
This code runs with no issues:
sample = {'Date': ['2015-07-02 11:47:00', '2015-08-02 11:30:00']}
dftest = pd.DataFrame.from_dict(sample)
dftest['Date'] = pd.to_datetime(dftest['Date'])
display(dftest.info())
dftest['year'] = dftest['Date'].dt.year
dftest['month'] = dftest['Date'].dt.month
This code gives me the error message:
sample = {'Date': ['2015-07-02 11:47:00', '2015-08-02 11:30:00']}
dftest = pd.DataFrame.from_dict(sample)
dftest['Date'] = pd.to_datetime(dftest['Date'])
def CALLYMD(dftest):
if dftest['Date'].dt.month>9:
return str(dftest['Date'].dt.year) + '1231'
elif dftest['Date'].dt.month>6:
return str(dftest['Date'].dt.year) + '0930'
elif dftest['Date'].dt.month>3:
return str(dftest['Date'].dt.year) + '0630'
else:
return str(dftest['Date'].dt.year) + '0331'
dftest['CALLYMD'] = dftest.apply(CALLYMD, axis=1)
Lastly, I'm open to any suggestions on how to make this code better as I'm still learning.
I'm guessing you should remove .dt in the second case. When you do apply it's applying to each element, .dt is needed when it's a group of data, if it's only one element you don't need .dt otherwise it will raise
{AttributeError: 'Timestamp' object has no attribute 'dt'}
reference: https://stackoverflow.com/a/48967889/13720936
After looking at the timestamp documentation, I found removing the .dt and just doing .year and .month works. However, I'm still confused as to why it works in the first code but does not work in the second code.
here is how to create a yearmonth bucket using the year and month
for key, item in df.iterrows():
year=pd.to_datetime(item['Date']).year
month=str(pd.to_datetime(item['Date']).month)
df.loc[key,'YearMonth']="{:.0f}{}".format(year,month.zfill(2))

cant change column name from 'NaN' to smth else

i have tried to string the column names and then change them - no succces, it left it NaN
data.rename(columns=str).rename(columns={'NaN':'Tip Analiza','NaN':'Limite' }, inplace=True)
i tried to use the in function to replace NaN- no succes - it gave an error,
TypeError: argument of type 'float' is not iterable
data.columns = pd.Series([np.nan if 'Unnamed:' in x else x for x in data.columns.values]).ffill().values.flatten()
what should i try ?
Try:
data.columns=map(str, data)
# in case of unique column names
data=data.replace({"col1": "rnm1", "col2": "rnm2"})
# otherwise ignore first line, and just do
data.columns=["rnm1", "rnm2"]

Openpyxl Bar graph Error bars

I was wondering if it is possible to set an error bar series to a reference. What I would like to do is reference cells with the error values already calculated. and then have it displayed on top of the bar graphs.
I found a similar question where they have seemed to do a version of what I am trying, but when I edit their example I get an error.
Any advice would be much appreciated. Thank you for your time.
Example of what I want the graph and error bars to look like
Error:
TypeError: expected class 'openpyxl.chart.error_bar.ErrorBars'
similar Question
openpyxl chart error bar styles
My Current Code
chart1 = BarChart()
chart1.type = "col"
chart1.height = 10
chart1.width = col + 7
chart1.title = name
data = Reference(ws, min_col=4, min_row=23, max_col=17)
cats = Reference(ws, min_col=4, min_row=29, max_col = 17)
eBars = Reference(ws, min_col=4, min_row=26, max_col=17)
s= Series(data)
series = SeriesFactory(data, title="y direction error")
series.errBars = eBars
chart1.append(s)
chart1.append(series)
chart1.legend = None
chart1.set_categories(cats)
chart1.x_axis.tickLblPos = "low"
#chart1.x_axis.tickLblSkip = 0
chart1.shape = 10
ws.add_chart(chart1, "C3")
Comment: ... setting a reference to the plus and minus
I see your point, replace numLitwith numRef:
NumDataSource / NumRef
class openpyxl.chart.data_source.NumDataSource(numRef=None, numLit=None)
`numLit` Values must be of type <class ‘openpyxl.chart.data_source.NumData’>
`numRef` Values must be of type <class ‘openpyxl.chart.data_source.NumRef’>
eBarsNumDataSource = NumDataSource(NumRef(eBars))
series.errBars = ErrorBars(errDir='y', errValType='cust', plus=eBarsNumDataSource, minus=eBarsNumDataSource)
Question: TypeError: expected class 'openpyxl.chart.error_bar.ErrorBars'
Your eBars is of Type Reference but you need Type openpyxl.chart.error_bar.ErrorBars.
class openpyxl.chart.error_bar.ErrorBars
class openpyxl.chart.error_bar.ErrorBars(
errDir=None,
errBarType='both',
errValType='fixedVal',
noEndCap=None, plus=None, minus=None, val=None, spPr=None, extLst=None)
You need at least the following Parameters:
ErrorBars(errDir=Value must be one of {‘x’, ‘y’},
plus=Values must be of type <class ‘openpyxl.chart.data_source.NumDataSource’>,
minus=Values must be of type <class ‘openpyxl.chart.data_source.NumDataSource’>,
)
Follow def list2errorbars(... in the linked similar Question.

Getting the value of a previous excel cell in python

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.

Categories

Resources