Here is my first question and I am totally newby in Python so bear with me!
I am developing a code and at this step I am trying to create a matrix with 2 rows and certain amount of columns. The first row is an array and the second is another array (with the same length), UaP and UbP as can be seen in the code hopefully.
As it can be seen UaP and UbP both are (1, 400), but when I try to create an array by combining two, the resulted matrix dimension will be (2,1,400) instead of expected 2 x 400 dimension.
I have tried different things but I dont get what I expected. Maybe there is a simple trick to solve it? Thanks in advance.
```python
import numpy as np
#some codes here
UaP = 0.5*(Ua-Ub90)
UbP = 0.5*(Ub+Ua90)
UabP = np.array([(UaP),(UbP)])
# shapes of arrays
UbP.shape
(1, 400)
UaP.shape
(1, 400)
UabP = np.array([(UaP),(UbP)])
UabP.shape
(2, 1, 400)
Thats because your first array has shape (1,400) instead of (400,).
You could try this:
import numpy as np
UaP = np.random.rand(1,400)
UbP = np.random.rand(1,400)
# first solution
UabP = np.array([UaP[0],UbP[0]])
print(UabP.shape)
# second soluton
UabP = np.array([UaP,UbP])
UabP = UabP.reshape(1,2,400)
UabP = UabP[0]
print(UabP.shape)
Related
how can I write a code that shows me the index of where the Newdate1 and Newdate2 is located within Setups. The value for Newdate1 within Setups is the second index which outputs 1 for result. The np.where function does not work however. How could I do this without a for loop?
import numpy as np
Setups = np.array(['2017-09-15T07:11:00.000000000', '2017-09-15T11:25:00.000000000',
'2017-09-15T12:11:00.000000000', '2017-12-22T03:14:00.000000000',
'2017-12-22T03:26:00.000000000', '2017-12-22T03:31:00.000000000',
'2017-12-22T03:56:00.000000000'],dtype="datetime64[ns]")
Newdate1 = np.array(['2017-09-15T07:11:00.000000000'], dtype="datetime64[ns]")
Newdate2 = np.array(['2017-12-22T03:26:00.000000000'], dtype="datetime64[ns]")
result = np.where(Setups == Newdate1)
result2 = np.where(Setups == Newdate2)
Expected Output:
result: 1
result2: 4
use np.in1d to pass the array to be searched within another array and get the indices using np.where.
import numpy as np
Setups = np.array(['2017-09-15T07:11:00.000000000', '2017-09-15T11:25:00.000000000',
'2017-09-15T12:11:00.000000000', '2017-12-22T03:14:00.000000000',
'2017-12-22T03:26:00.000000000', '2017-12-22T03:31:00.000000000',
'2017-12-22T03:56:00.000000000'],dtype="datetime64[ns]")
newdates = np.array(['2017-09-15T07:11:00.000000000','2017-12-22T03:26:00.000000000'],dtype="datetime64[ns]")
print(np.where(np.in1d(Setups,newdates)))
output:
(array([0, 4]),)
I am trying to calculate the mean average of columns from a list of arrays.
f1_score = [array([0.807892 , 0.91698113, 0.73846154]),
array([0.80041797, 0.9056244 , 0.72017837]),
array([0.80541103, 0.91493384, 0.70282486])]
I also tried as mentioned below, but I couldn't get the mean value for columns.
output = []
for i in range(len(f1_score)):
output.append(np.mean(f1_score[i], axis = 0))
I get the mean values for rows:
[0.8211115582302323, 0.8087402497928408, 0.8077232421210242]
But I need the mean values for columns:
array([0.8045736667, 0.9125131233, 0.7204882567])
Thanks in advance for your answer.
You can use numpy's mean function and set the axis as 0.
mean(f1_score, axis=0)
And then you get the required answer
array([0.80457367, 0.91251312, 0.72048826])
If you dont mind using numpy you can do the following
import numpy as np
arr = np.random.randint(0,10,size=(2,2)) #sample data
arr
#array([[0, 2],
# [6, 1]])
arr.mean(axis=0) #mean along the columns
# array([3. , 1.5])
arr.mean(axis=1) #mean along the rows
# array([1. , 3.5])
Alternatively, you can find the means by doing the following
arr = [[0,2], [6,1]]
col_means = [sum(i)/len(i) for i in zip(*arr)] #column wise means
# [3.0, 1.5]
row_means = [sum(i)/len(i) for i in arr] #row wise means
# [1.0, 3.5]
Try this:
f1_score = [[0.807892 , 0.91698113, 0.73846154],[0.80041797, 0.9056244 ,0.72017837],[0.80541103, 0.91493384, 0.70282486]]
temp=[]
output = []
for i in range(len(f1_score)):
for j in range(len(f1_score)):
temp.append(f1_score[j][i])
output.append(np.mean(temp))
print(output)
in Swift Playgrounds I have solved a level where I had to place 16 Blocks at specific coordinates.
for example:
let B1 = Block;
world.place(B1, atColumn: 1, row: 6)
If you have to do this 16 times, it is kind of lot to write down and doesn’t look really good. So my Question is if it is possible to create an array with coordinates (if yes, how can I do that) to just need to write something like that:
world.place(Block(), at: coordinate)
Thank you already for your time and your answers.
You can create an array of named tuples and then loop over that array placing a block at each one:
let coordinates: [(column: Int, row: Int)] = [(1, 2), (3, 4)]
for coordinate in coordinates {
let B1 = Block
world.place(B1, atColumn: coordinate.column, row: coordinate.row)
}
or you can unpack the column and row directly by using:
for (column, row) in coordinates {
let B1 = Block
world.place(B1, atColumn: column, row: row)
}
Good afternoon.
I've been struggling with this for a while now, and although I can find similiar problems online, nothing I found could really help me resolve it.
Starting with a standard data file (.csv or .txt, I tried both) containing three columns (x, y and the error of y), I want to read in the data and generate a line plot including error bars.
I can plot the x and y values without a problem, but if I want to add errorbars using the matplotlib.pyplot errorbar utility, I get the following error message:
ValueError: yerr must be a scalar, the same dimensions as y, or 2xN.
The code below works if I use some arbitrary arrays (numpy or plain python), but not for data read from the file. I've tried converting the tuples which I obtain from my input code to numpy arrays using asarray, but to no avail.
import numpy as np
import matplotlib.pyplot as plt
row = []
with open("data.csv") as data:
for line in data:
row.append(line.split(','))
column = zip(*row)
x = column[0]
y = column[1]
yer = column[2]
plt.figure()
plt.errorbar(x,y,yerr = yer)
fig = plt.gcf()
fig.set_size_inches(18.5, 10.5)
fig.savefig('example.png', dpi=300)
It must be that I am overlooking something. I would be very grateful for any thoughts on the matter.
yerr should be the added/subtracted error from the y value. In your case the added equals the subtracted equals half of the third column.
import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt('data.csv', delimiter=',')
plt.figure()
yerr_ = np.tile(data[:, 2]/2, (2, 1))
plt.errorbar(data[:, 0], data[:, 1], yerr=yerr_)
plt.xlim([-1, 3])
plt.show()
data.csv
0,2,0.3
1,4,0.4
2,3,0.15
I am trying to wrote a program to manage a Database through a Scala Gui, and have been running into alot of trouble formatting my data in such a way as to input it into a Table and have the Column Headers populate. To do this, I have been told I would need to use an Array[Array[Any]] instead of an ArrayBuffer[ArrayBuffer[String]] as I have been using.
My problem is that the way I am trying to fill these arrays is modular: I am trying to use the same function to draw from different tables in a MySQL database, each of which has a different number of columns and entries.
I have been able to (I think) define a 2-D array with
val Data = new Array[Array[String]](numColumns)(numRows)
but I haven't found any ways of editing individual cells in this new array.
Data(i)(j)=Value //or
Data(i,j)=Value
do not work, and give me errors about "Update" functionality
I am sure this can't possibly be as complicated as I have been making it, so what is the easy way of managing these things in this language?
You don't need to read your data into an Array of Arrays - you just need to convert it to that format when you feed it to the Table constuctor - which is easy, as demonstrated my answer to your other question: How do I configure the Column names in a Scala Table?
If you're creating a 2D array, the idiom you want is
val data = Array.ofDim[String](numColumms, numRows)
(There is also new Array[String](numColumns, numRows), but that's deprecated.)
You access element (i, j) of an Array data with data(i)(j) (remember they start from 0).
But in general you should avoid mutable collections (like Array, ArrayBuffer) unless there's a good reason. Try Vector instead.
Without knowing the format in which you're retrieving data from the database it's not possible to say how to put it into a collection.
Update:
You can alternatively put the type information on the left hand side, so the following are equivalent (decide for yourself which you prefer):
val a: Array[Array[String]] = Array.ofDim(2,2)
val a = Array.ofDim[String](2,2)
To explain the syntax for accessing / updating elements: as in Java, a multi-dimensional array is just an array of arrays. So here, a(i) is element i of a, which an Array[String], and so a(i)(j) is element j of that array, which is a String.
Luigi's answer is great, but I'd like to shed some light on why your code isn't working.
val Data = new Array[Array[String]](numColumns)(numRows)
does not do what you expect it to do. The new Array[Array[String]](numColumns) part does create an array of array of strings with numColumns entries, with all entries (arrys of strings) being null, and returns it. The following (numRows) then just calls the apply function on that returned object, which returns the numRowsth entry in that list, which is null.
You can try that out in the scala REPL: When you input
new Array[Array[String]](10)(9)
you get this as output:
res0: Array[String] = null
Luigi's solution, instead
Array.ofDim[String](2,2)
does the right thing:
res1: Array[Array[String]] = Array(Array(null, null), Array(null, null))
It's rather ugly, but you can update a multidimensional array with update
> val data = Array.ofDim[String](2,2)
data: Array[Array[String]] = Array(Array(null, null), Array(null, null))
> data(0).update(0, "foo")
> data
data: Array[Array[String]] = Array(Array(foo, null), Array(null, null))
Not sure about the efficiency of this technique.
Luigi's answer is great, but I just wanted to point out another way of initialising an Array that is more idiomatic/functional – using tabulate. This takes a function that takes the array cell coordinates as input and produces the cell value:
scala> Array.tabulate[String](4, 4) _
res0: (Int, Int) => String => Array[Array[String]] = <function1>
scala> val data = Array.tabulate(4, 4) {case (x, y) => x * y }
data: Array[Array[Int]] = Array(Array(0, 0, 0, 0), Array(0, 1, 2, 3), Array(0, 2, 4, 6), Array(0, 3, 6, 9))