How to append an array within a for loop that gets new outputs every loop?
array2 = np.array([])
for i in range(len(fps)):
array1 = np.array([])
DataStructs.ConvertToNumpyArray((fps[i]), array1)
# you need to assign the concatenated array to array2
array2 = np.append(array2,array1)
array2
# if you want to have a 2D-array as output, you can do the following:
# initialize the array then assign new elements to it
array2 = np.zeros(shape=(len(fps),1024))
for i in range(len(fps)):
array1 = np.array([])
DataStructs.ConvertToNumpyArray((fps[i]), array1)
array2[i] = array1
array2
# or you can use np.concatenate
array2 = np.zeros(shape=(0,1024))
for i in range(len(fps)):
array1 = np.array([])
DataStructs.ConvertToNumpyArray((fps[i]), array1)
array2 = np.concatenate((array2,[array1]))
Append list array in for loop
I'm not an expert on masked arrays but this works:
# create example
>>> a = np.arange(30).reshape(10, 3)
>>> a[[0,7,8]] = 0
>>> a = np.ma.MaskedArray(a, np.isin(a // 3, (2,3)))
>>>
>>> a
masked_array(
data=[[0, 0, 0],
[3, 4, 5],
[--, --, --],
[--, --, --],
[12, 13, 14],
[15, 16, 17],
[18, 19, 20],
[0, 0, 0],
[0, 0, 0],
[27, 28, 29]],
mask=[[False, False, False],
[False, False, False],
[ True, True, True],
[ True, True, True],
[False, False, False],
[False, False, False],
[False, False, False],
[False, False, False],
[False, False, False],
[False, False, False]],
fill_value=999999)
>>>
# cut all rows that have at least one masked or all zero entries
>>> compressed = a.data[~np.any(a.mask, axis=1) & np.any(a.data!=0, axis=1)]
>>> compressed
array([[ 3, 4, 5],
[12, 13, 14],
[15, 16, 17],
[18, 19, 20],
[27, 28, 29]])
List append() in for loop raises exception: 'NoneType' object has no attribute 'append'
The list.append
function does not return any value(but None
), it just adds the value to the list you are using to call that method.
In the first loop round you will assign None
(because the no-return of append
) to a
, then in the second round it will try to call a.append
, as a is None
it will raise the Exception you are seeing
You just need to change it to:
a = []
for i in range(5):
# change a = a.append(i) to
a.append(i)
print(a)
# [0, 1, 2, 3, 4]
list.append
is what is called a mutating or destructive method, i.e. it will destroy or mutate the previous object into a new one(or a new state).
If you would like to create a new list based in one list without destroying or mutating it you can do something like this:
a=['a', 'b', 'c']
result = a + ['d']
print result
# ['a', 'b', 'c', 'd']
print a
# ['a', 'b', 'c']
As a corollary only, you can mimic the append
method by doing the following:
a = ['a', 'b', 'c']
a = a + ['d']
print a
# ['a', 'b', 'c', 'd']
Python append to array and for loop for it
Can you try this?
{''}
means its a set
and you only want the element in the set
. And pop
gives that
for x in sidra:
link = x.absolute_links.pop()
links.append(link)
How do you loop an array and append it to a div?
You have to loop the array. Using .forEach() you can use the two arguments that are provided:
item
index
.
At each loop iteration, using the item
, you can access the objects properties like className
, urlSrc
and labelName
.
Using the index
, you can target the right a
element with the .eq() method.
You will also notice the use of templating literals to insrt the variables in the string to append.
var arrayTest = [
{
className: "class-01",
urlSrc: "http://via.placeholder.com/100x100?text=Image 1",
labelName: "01 Label Name"
},
{
className: "class-02",
urlSrc: "http://via.placeholder.com/100x100?text=Image 2",
labelName: "02 Label Name"
},
{ className: "class-03",
urlSrc: "http://via.placeholder.com/100x100?text=Image 3",
labelName: "03 Label Name"
}
];
$(document).ready(function () {
arrayTest.forEach(function (item, index) {
$("#menu a").eq(index).append(
`<div class="${item.className}">
<span class='vertical-align-middle'></span>
<img src="${item.urlSrc}">
</div>
<div class='filter-label'>${item.labelName}</div>`
);
});
});
a{
text-decoration: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="menu" class="menu">
<li id="menu-item-1">
<a href="#">
</a>
</li>
<li id="menu-item-2">
<a href="#">
</a>
</li>
<li id="menu-item-3">
<a href="#">
</a>
</li>
</ul>
Append array in for loop
List append is always better than np.append
. It is faster, and easier to use correctly.
But let's look at your code in more detail:
In [128]: df = pd.DataFrame(np.random.choice([0.0, 0.05], size=(1000,1000)))
In [129]: l = np.array([])
In [130]: rand_cols = np.random.permutation(df.columns)[0:5]
In [131]: rand_cols
Out[131]: array([190, 106, 618, 557, 514])
In [132]: df2 = df[rand_cols].copy()
In [133]: df2.shape
Out[133]: (1000, 5)
In [134]: l1 = np.append(l, df2, axis=0)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-134-64d82acc3963> in <module>
----> 1 l1 = np.append(l, df2, axis=0)
/usr/local/lib/python3.6/dist-packages/numpy/lib/function_base.py in append(arr, values, axis)
4692 values = ravel(values)
4693 axis = arr.ndim-1
-> 4694 return concatenate((arr, values), axis=axis)
4695
4696
ValueError: all the input arrays must have same number of dimensions
Since you specified the axis, all np.append
is doing is:
np.concatenate([l, df2], axis=0)
l
is (0,) shape, df2
is (1000,5). 1d and 2d, hence the complaint about dimensions.
Starting with a 2d l
array works:
In [144]: l = np.zeros((0,5))
In [145]: np.concatenate([l, df2], axis=0).shape
Out[145]: (1000, 5)
In [146]: np.concatenate([df2, df2], axis=0).shape
Out[146]: (2000, 5)
I think np.append
should be deprecated. We see too many SO errors. As your case shows, it is hard to create the correct initial array. np.array([])
only works when building a 1d array. Plus repeated concatenates are slow, creating a completely new array each time.
How to append a list to another list in a python for loop when each element of the existing list is being changed inside the for loop?
When you append r1
twice to r2
it essentially makes r2
a list of [r1, r1]
not the contents of r1
when it was appended, so when r1
is changed before the second append, the first element in r2
which is a reference to r1
is also changed.
One solution is to not use r1 at all and just append the contents directly:
r2 = []
r_1 = {'G':32,'H':3}
for i in r_1:
r2.append([i, i+"I"])
print(r2)
A second solution is to append a copy of r1 to avoid the two elements having the same reference:
r2 = []
r_1 = {'G':32,'H':3}
r1 = [None, None]
for i in r_1:
r1[0] = i
r1[1] = i + "I"
r2.append(r1.copy())
print(r2)
Related Topics
How to Call Python Script on Excel Vba
Loop Through Json Data in Python
How to Convert Column With Dtype as Object to String in Pandas Dataframe
How to Convert a Float into Hex
Valueerror: Invalid \Escape Unable to Load Json from File
Filtering Dataframe Using the Length of a Column
Python - Remove Any Element from a List of Strings That Is a Substring of Another Element
How to Make Multiple Empty Lists in Python
Numpy Import Throws Attributeerror: 'Module' Object Has No Attribute 'Core'
How to Skip Empty Dates (Weekends) in a Financial Matplotlib Python Graph
How to Transform Floats to Integers in a List
Optimal Way to Store Data from Pandas to Snowflake
How to Convert Dict Value to a Float
Count Duplicates Between 2 Lists
If-Condition With Multiple Actions in Robot Framework
Deleting Dataframe Row in Pandas If a Combination of Column Values Equals a Tuple in a List