'How to create a new blank array within a function in Python?
I have a function that extracts a column of data from a parent array, but I don't know how to make the function create a new blank array for this data to be stored in.
The function has two variables "title" and "column", where "title" would be the desired name of the new array for the extracted data (currently I just input the name of a pre-defined array), and "column" defines which column in the parent array is to be extracted.
I should also state I'm using a Jupyter notebook.
Here's the code:
def extract_col(title, column):
title = [data[:,column]]
Where "data" in the code is just the name of the parent array. Here's an example:
extract_col(array1, 3)
This input should create an array called array1, which consists of column 3 of the parent array, "data".
Solution 1:[1]
You can achieve the goal using this (this creates a variable like you are wanting):
def extract_col(title, column):
locals()[title] = data[:,column]
However you should not use locals() to make a new variable for this (or ever). Instead use a dictionary, not a variable:
def extract_col(title, column):
d = {}
d[title] = data[:,column]
Then you can just call d[title] where you need it.
If you are using np.array() and want a new empty array as you mention in the question you can use:
def extract_col(title, column):
d = {}
d[title] = np.array([])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jmd_dk |
