logo
down
shadow

Adding an extra in column into 2D numpy array python


Adding an extra in column into 2D numpy array python

Content Index :

Adding an extra in column into 2D numpy array python
Tag : python , By : Tamizhvendan
Date : November 28 2020, 04:01 AM

like below fixes the issue Using np.insert()
>>> import numpy as np
>>> arr
array([[-0.30368954,  2.8808107 ,  5.8833385 ,  8.6606045 , 11.242557  ],
       [-0.22719575,  3.0030012 ,  6.065371  ,  8.924864  , 11.561942  ]],

>>> arr = np.insert(arr, 0, np.nan, axis=0)
>>> arr
array([[        nan, -0.30368954,  2.8808107 ,  5.8833385 ,  8.6606045 , 11.242557  ],
       [        nan, -0.22719575,  3.0030012 ,  6.065371  ,  8.924864  , 11.561942  ]],

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How to add an extra column to a NumPy array


Tag : python , By : AdrianB
Date : March 29 2020, 07:55 AM
I wish did fix the issue. I think a more straightforward solution and faster to boot is to do the following:
import numpy as np
N = 10
a = np.random.rand(N,N)
b = np.zeros((N,N+1))
b[:,:-1] = a
In [23]: N = 10

In [24]: a = np.random.rand(N,N)

In [25]: %timeit b = np.hstack((a,np.zeros((a.shape[0],1))))
10000 loops, best of 3: 19.6 us per loop

In [27]: %timeit b = np.zeros((a.shape[0],a.shape[1]+1)); b[:,:-1] = a
100000 loops, best of 3: 5.62 us per loop

determining repeated values in numpy array and adding them in another column python


Tag : python , By : Debashree
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , If I understand correctly, you want the first column in your output to be the full sequence of values in w (including repetitions), and the second column to be the counts for each value (also repeated for repeated values in w)?
You can do this using np.unique by returning both the item counts and the set of 'inverse' indices that reconstruct the original array from the unique values (in the example below, uvals[idx] would give you back w). You can use the inverse indices to index into the count values according to wherever the corresponding unique items occur within w:
w = np.array([1, 3, 4, 5, 6, 2, 9, 2, 4, 2, 1, 3, 3, 6])
uvals, idx, counts = np.unique(w, return_counts=True, return_inverse=True)
out = np.vstack((w, counts[idx])).T

print(out)
# [[1 2]
#  [3 3]
#  [4 2]
#  [5 1]
#  [6 2]
#  [2 3]
#  [9 1]
#  [2 3]
#  [4 2]
#  [2 3]
#  [1 2]
#  [3 3]
#  [3 3]
#  [6 2]]

Python: adding values to a numpy bool array column-wise


Tag : arrays , By : user161314
Date : March 29 2020, 07:55 AM
may help you . I have a list of values and a numpy bool array that looks like the following: , Use transpose method:
import numpy as np
boo = np.array([[False, True, True, False, False, True],
                [True, True, True, False, False, True],
                [True, True, True, True, True, True]])
x = np.zeros(boo.shape, dtype=int)
y = np.array([1, 7, 2, 2, 3, 7, 1, 1, 4, 2, 9, 1, 2])
x.T[boo.T] = y
print(x)

[[0 2 7 0 0 9]
 [1 2 1 0 0 1]
 [7 3 1 4 2 2]]

Issue when extending a matrix-like numpy array by adding extra list


Tag : python , By : akr
Date : March 29 2020, 07:55 AM
hope this fix your issue I wrote the following code that does: (1) Generate root matrix of shape (3, 16), and (2) Generate 1000 binary vectors C such that each vector is added at the end of the root matrix iteratively one at a time. , If you can swap this:
batch = root[i:(i + (len(root)))]
batch = np.append(batch, C[i])
batch = np.append(batch, [C[i]], axis=0)

numpy array concatenate with extra column to each array


Tag : development , By : user87225
Date : March 29 2020, 07:55 AM
To fix the issue you can do I try to split a numPy array in roughly equal parts and merge them together with an extra value but end up being confused how I could do this. I have a list : [0., 2.25, 4., 4., 4., 4., 4., 4., 4., 2.25], which after an np.array_split and concatenate with an extra column should end up like: [0. , 2.25, 4., 8., 4., 4., 4., 8., 4., 4., 8., 4. , 2.25]
In [71]: alist = [0., 2.25, 4., 4., 4., 4., 4., 4., 4., 2.25]
In [72]: x = np.array(alist)
In [73]: xs = np.array_split(x, 4)
In [75]: xs
Out[75]: 
[array([0.  , 2.25, 4.  ]),
 array([4., 4., 4.]),
 array([4., 4.]),
 array([4.  , 2.25])]
In [76]: np.concatenate(xs)
Out[76]: array([0.  , 2.25, 4.  , 4.  , 4.  , 4.  , 4.  , 4.  , 4.  , 2.25])
In [77]: np.array(xs)
Out[77]: 
array([array([0.  , 2.25, 4.  ]), array([4., 4., 4.]), array([4., 4.]),
       array([4.  , 2.25])], dtype=object)
In [79]: np.array_split(x,5)
Out[79]: 
[array([0.  , 2.25]),
 array([4., 4.]),
 array([4., 4.]),
 array([4., 4.]),
 array([4.  , 2.25])]
In [80]: np.array(np.array_split(x,5))
Out[80]: 
array([[0.  , 2.25],
       [4.  , 4.  ],
       [4.  , 4.  ],
       [4.  , 4.  ],
       [4.  , 2.25]])
In [84]: for i,v in enumerate(xs[:-1]):
    ...:     xs[i] = np.concatenate([v,[8]])
    ...:     
In [85]: xs
Out[85]: 
[array([0.  , 2.25, 4.  , 8.  ]),
 array([4., 4., 4., 8.]),
 array([4., 4., 8.]),
 array([4.  , 2.25])]
In [86]: np.concatenate(xs)
Out[86]: 
array([0.  , 2.25, 4.  , 8.  , 4.  , 4.  , 4.  , 8.  , 4.  , 4.  , 8.  ,
       4.  , 2.25])
Related Posts Related QUESTIONS :
  • Add multiple EntityRuler with spaCy (ValueError: 'entity_ruler' already exists in pipeline)
  • error when replacing missing ')' using negative look ahead regex in python
  • Is there a way to remove specific strings from indexes using a for loop?
  • select multiple tags by position in beautifulSoup
  • pytest: getting AttributeError: 'CaptureFixture' object has no attribute 'readouterror' capturing stdout
  • Shipping PyGObject/GTK+ app on Windows with MingW
  • Python script to deduplicate lines in multiple files
  • How to prevent window and widgets in a pyqt5 application from changing size when the visibility of one widget is altered
  • How to draw stacked bar plot from df.groupby('feature')['label'].value_counts()
  • Python subprocess doesn't work without sleep
  • How can I adjust 'the time' in python with module Re
  • Join original np array with resulting np array in a form of dictionary? multidimensional array? etc?
  • Forcing labels on histograms in each individual graph in a figure
  • For an infinite dataset, is the data used in each epoch the same?
  • Is there a more efficent way to extend a string?
  • How to calculate each single element of a numpy array based on conditions
  • How do I change the width of Jupyter notebook's cell's left part?
  • Measure distance between lat/lon coordinates and utm coordinates
  • Installing megam for NLTK on Windows
  • filter dataframe on each value of a samn column have a specific value of another column in Panda\Python
  • Threading with pubsub throwing AssertionError: 'callableObj is not callable' in wxPython
  • Get grouped data from 2 dataframes with condition
  • How can I import all of sklearns regressors
  • How to take all elements except the first k
  • Whats wrong with my iteration list of lists from csv
  • Tensorflow Estimator API save image summary in eval mode
  • How to Pack with PyQt - how to make QFrame/Layout adapt to content
  • How do I get certain Time Range in Python
  • python doubly linked list - insertAfter node
  • Open .h5 file in Python
  • Joining a directory name with a binary file name
  • python, sort list with two arguments in compare function
  • Is it possible to print from Python using non-ANSI colors?
  • Pandas concat historical data using date minus some number of days
  • CV2: Import Error in Python OpenCV
  • Is it possible to do this loop in a one-liner?
  • invalid literal for int() with base 10: - django
  • Why does my code print a value that I have not assigned as yet?
  • the collatz func in automate boring stuff with python
  • How to find all possible combinations of parameters and funtions
  • about backpropagation deep neural network in tensorflow
  • Sort strings in pandas
  • How do access my flask app hosted in docker?
  • Replace the sentence include some text with Python regex
  • Counting the most common element in a 2D List in Python
  • logout a user from the system using a function in python
  • mp4 metadata not found but exists
  • Django: QuerySet with ExpressionWrapper
  • Pandas string search in list of dicts
  • Decryption from RSA encrypted string from sqlite is not the same
  • need of maximum value in int
  • a list of several tuples, how to extract the same of the first two elements in the small tuple in the large tuple
  • Display image of 2D Sinewaves in 3D
  • how to prevent a for loop from overwriting a dictionary?
  • How To Fix: RuntimeError: size mismatch in pyTorch
  • Concatenating two Pandas DataFrames while maintaining index order
  • Why does this not run into an infinite loop?
  • Python Multithreading no current event loop
  • Element Tree - Seaching for specific element value without looping
  • Ignore Nulls in pandas map dictionary
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com