I am trying to write a cell array to an Excel spreadsheet in Octave using the xlswrite from the io package in Octave (3.8.0, io 2.0.2 loaded, using Windows 7 64 bit).
The cell array looks like this:
>> pump_backlash(1:3,:)
ans =
{
[1,1] = Machine #
[2,1] = Machine_01
[3,1] = Machine_02
[1,2] = Station #
[2,2] = 1
[3,2] = 1
[1,3] = Pump channel #
[2,3] = 1
[3,3] = 2
[1,4] = Backlash
[2,4] =
57 65 62
[3,4] =
58 49 50
}
Except it's got many more rows. The first row consists of "headings" (strings), and then after that the first column is a string relating to the machine ID, the second and third columns are integers (scalars), and the fourth column of the cell array are 1x3 vectors of integers (although cells in the 4th column are sometimes empty if the test/measurement failed for whatever reason).
I try to write to Excel using the following command:
>> xlswrite('Pump_cal_results.xlsx',pump_backlash)
and the error message I get is as follows:
Creating file Pump_cal_results.xlsx
error: cellfun: all values must be scalars when UniformOutput = true
error: called from:
error: C:\Octave\Octave-3.8.0\share\octave\packages\io-2.0.2\private\spsh_prstype.m at line 62, column 6
error: C:\Octave\Octave-3.8.0\share\octave\packages\io-2.0.2\private\__COM_oct2spsh__.m at line 108, column 10
error: C:\Octave\Octave-3.8.0\share\octave\packages\io-2.0.2\oct2xls.m at line 189, column 18
error: C:\Octave\Octave-3.8.0\share\octave\packages\io-2.0.2\xlswrite.m at line 178, column 20
If I follow the error trail and go to line 62 of \private\spsh_prstype.m, I have:
ptr = cellfun ("isnan", obj); ## Find NaNs & set to BLANK
So it's obviously got something to do with that function call to cellfun, but I am not sure where to go from there. There are quite a few other function calls to cellfun in spsh_prstype.m.
The closest I have found by searching on the internet is this question, but there is no solution offered.
Any help/suggestions welcome.
Not having received any answers, I'll answer my own question :-)
I haven't worked out what the root cause of the problem and how to fix it, but I have found a workaround. It seems that the problems lies with the fact that the elements in the 4th column are vectors rather than scalars. It seems that to write to Excel, all elements in the cell array must be "uniform", which I take it to mean you can't mix scalars and vectors for example.
So my workaround was to re-arrange the cell array so that it now looks like:
>> pump_backlash(1:3,:)
ans =
{
[1,1] = Machine #
[2,1] = Machine_01
[3,1] = Machine_02
[1,2] = Station #
[2,2] = 1
[3,2] = 1
[1,3] = Pump channel #
[2,3] = 1
[3,3] = 2
[1,4] = Backlash #1
[2,4] = 57
[3,4] = 58
[1,5] = Backlash #2
[2,5] = 65
[3,5] = 49
[1,6] = Backlash #3
[2,6] = 62
[3,6] = 50
}
i.e. the cell array now has 6 columns instead of 4, and there's no more vectors, only scalars.
The call to xlswrite then works OK:
xlswrite('Pump_cal_results.xlsx',pump_backlash,'Backlash','','com');
Related
This question already has answers here:
How to get the cartesian product of multiple lists
(17 answers)
Closed 2 years ago.
I have the following two lists:
x = [1,2]
y = [4,5,6]
I want to iterate x by z.
I have a variable called code set to NONE and another variable called value also set to NONE. Here is the output I am aiming for:
1st iteration, code = 1 and value = 4
2nd iteration, code = 1 and value = 5
3rd iteration, code = 1 and value = 6
4th iteration, code = 2 and value = 4
5th iteration, code = 2 and value = 5
6th iteration, code = 2 and value = 6
Here is what I have tried:
x = [1, 2]
y = [4, 5, 6]
code = None
value = None
for x_ids, y_ids in zip(x, y):
code = x_ids
value = y_ids
print("c", code)
print("v", value)
output:
c 1
v 4
c 2
v 5
Can anyone suggest how to get the output described above?
This is one way to achieve what you're looking for:
x = [1, 2]
y = [4, 5, 6]
code = None
value = None
iter_count = 0
for x_ids in x:
code = x_ids
for y_ids in y:
iter_count += 1
value = y_ids
print('{} iteration, code = {} and value = {}'.format(iter_count, code, value))
#print(str(iter_count) + ' iteration, code = ' + str(code) + 'and value = ' + str(value))
Like discussed in the comments, this code iterates through all elements of y for every element in x. In your original code, you were iterating through both lists all at ones, using zip. Since you want to print the number of iteration too, there is a new variable, iter_count, that counts and stores those.
The code has two print statements, they print the same messages. The commented out one concatenates strings, and numbers converted to strings. The uncommented one may be less intuitive but it is often more useful and cleaner. It's worth looking at it, you can find an introduction here.
Last thing, if you need that too - to print numbers in 1st, 2nd etc. format you can use some of these approaches.
I have a list of lists, 24 with indexes 0-23 representing hours of the day. There are some that are empty but I have even tried filling them with 0s. I am trying to t test starting at the first list vs the next one, and if p>.05 then append the lists together, then test the combined list vs the next list. If p<.05 then they won't be combined and the next pair of lists will be tested. For example, if list 5 vs 6 gives p>.05 a new list of 5&6 is created and tested vs 7, if this is also p>.05 then 7 is appended to the list and the whole list is tested vs 8, etc. If 5&6 vs 7 is p<.05 then they will not be appended and 7 will be tested vs 8 instead and the process starts over. I have this code currently:
TestList=[]
for i in range(0,24):
TestList.append([])
for temp in paxbinfull.itertuples():
for i in range(int(temp.Pax)):
TestList[int(temp.hr)].append(int(temp.bucket)*10)
TestList = [[int(j) for j in i] for i in TestList]
for i in range(len(TestList)):
if TestList[i] ==[]:
TestList[i] = [1]
from scipy.stats import ttest_ind
i = 0
j = 1
left_list = TestList[0]
right_list = TestList[1]
list_groups = {}
while i <= 22:
p = ttest_ind(left_list,right_list,equal_var=False,nan_policy='omit')[1]
if p >= 0.05:
left_list.append(right_list)
elif p < 0.05:
list_groups[i] = left_list
left_list = TestList[j]
right_list = TestList[j+1]
i = i+1
j = j+1
I get an error that says "TypeError: unsupported operand type(s) for +: 'int' and 'list'" and it says it is from this line of the module: arrmean = umr_sum(arr, axis, dtype, keepdims=True).
Any help is appreciated, I feel like the logic is ok but maybe not? No idea what the problem is I can't understand the error.
List of lists that contains all the data that I am t-testing
i want to filetr my csv file using multiple value. For example
NEID VPNID DSCP COS
0 2645 1 18 1
1 2645 1 48 6
2 2645 2 34 2
3 2645 2 46 6
4 2645 3 46 6
I want to filter row whose value in DSCP column must match 18 and 48 (user defined)
import pandas as pd
df = pd.read_csv ("C:\Users\mnarwal\.PyCharmCE2019.1\config\scratches\VIL.csv")
print(df.head())
print(df.columns)
print(df.shape)
dscp1 = raw_input("DSCP1 Value = ")
dscp2 = raw_input("DSCP2 Value = ")
print(df.query([(df['DSCP'] == dscp1) & (df['DSCP'] == dscp2)]))
But above code is not running as per expectations as giving below error
C:\Python27\lib\site-packages\pandas\core\ops.py:1649: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
result = method(y)
Traceback (most recent call last):
File "C:/Users/mnarwal/.PyCharmCE2019.1/config/scratches/test.py", line 8, in <module>
print(df.query([(df['DSCP'] == dscp1) & (df['DSCP'] == dscp2)]))
File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 3085, in query
raise ValueError(msg.format(type(expr)))
ValueError: expr must be a string to be evaluated, <type 'list'> given
Process finished with exit code 1
You don't need to use query to acquire that slice:
print(df[(df['DSCP'] == dscp1) & (df['DSCP'] == dscp2)])
It is worth pointing out, though, that the slicing used above will never return anything - it is impossible to have two different values in the same row for DSCP column.
If you wanted to use query method, you would have to provide a query string, rather than using series slicing syntax.
Query method equivalent would look roughly like this:
print(df.query(f'DSCP == {dscp1} & DCP == {dscp2}'))
Read up more on querying here.
If I understood well, this will work.
def filter_my_df(x, y):
return df[(df['DSCP'] == x) | (df['DSCP'] == y)]
new_df = filter_my_df(18, 48)
I don't think "&" will work because the value cannot be 18 and 48 at the same time. That's why I used "|" instead.
Regards
I'm trying to forecasts time-series using a VECM with one endogenous and one exogenous variable (ideally both would be ex. but this doesn't seem to be possible), but keep running into errors. I've got 169 time-series and I'm trying to use the first 140 weeks to predict the last 29. See my code below:
#VECM with exogenous F
#read F and W matrix
Ffactor <- read_excel("FFactor.xlsx", col_names = FALSE)
Wfactor <- read_excel("Wmatrix.xlsx", col_names = FALSE)
Sales<-read_excel("SALES.xlsx")
Wfactor$mean <- rowMeans(Wfactor)
KC_model <- cbind(Sales$UnitSalesKC[1:169], Wfactor$mean)
F140 <- as.data.frame(Ffactor[1:140,])
for (i in 1:1000)
{
colnames(F140)[i]<-"f"
}
KC140 <- as.data.frame(KC_model[1:140,])
vecm <- ca.jo(KC140,type = "eigen", ecdet = "const", K = 2, dumvar = F140[1:140,1])
varr <- vec2var(vecm, r=1)#should be 2 because of 2nd order cointegration but it had to be 1
dumvar <- Ffactor[141:169,]
dumvar1 <- as.matrix(dumvar)
predictions <- predict(varr, dumvar=dumvar1[1:29], n.ahead=29)
predictions <- predict(varr, dumvar=dumvar1[1:29], n.ahead=29)
Running the first predict gives: Error in predict.vec2var(varr, dumvar = dumvar[1:29, 1], n.ahead = 29) :
Column names of 'dumvar' do not match with column names in 'object$datamat'.
Running the second one gives: Error in predict.vec2var(varr, dumvar = dumvar1[1:29, 1], n.ahead = 29) :
Number of rows of 'dumvar' is not equal to 'n.ahead'.
However, calling nrow(dumvar) yields 29.
I've previously gotten error telling me dumvar should be a matrix, numeric or vector which is why I converted it into a matrix. Here's a sample of all the data needed to run the above code.
#head of KC_model
1 125489.0 -0.427423755
2 115475.0 -0.590675518
3 124298.0 -0.561800218
4 128443.0 -0.785542240
5 120610.0 -0.750909402
#head of FFactor
1 -0.251
2 -0.0169
3 -0.0434
4 -0.0643
5 0.0215
Try this:
predictions <- predict(varr, dumvar=as.matrix.data.frame(F140[1:140,1]), n.ahead=29)
It worked for me.
So I have a matrix like:
1 2 3 4
0 3 4 1
7 3 4 5
And I want to select a row,then use this row to do stuff on it such as sorting it with some algorithms;I made this so far:
def row_management(matrix):
theline = input('wich line?') #enter row number
thelist = [matrix[theline]] #go take the right row of the matrix
menu_thelist(thelist) #supossed to use the row and take it to the list management menu
However, when I run this, it always return an error "[matrix[theline]] TypeError: list indices must be integers, not str" and I don't get it.
The input call returns a str type, so it can not be used directly as index to the list inmatrix[theline], which is also what the error message says. Instead do:
matrix[int(theline)]
Needed to convert to int
theline = int(input('wich line?'))
And also
thelist = matrix[theline]
the have [1,2,3] and not [[1,2,3]](wich cause further problem)