I feel like I'm going insane because I can't figure out what feels like should be a simple problem. I want to generate fake data in a numpy array and I can't figure out how to repeat a row of observations. I'd rather generate thousands of rows and I can't figure out how to repeat a row whenever I feel like.
For example, here's my current code:
voters = np.array(
[
['Democrat', 'Republican', 'Third'],
['Democrat', 'Republican', 'Third'],
['Democrat', 'Republican', 'Third'],
['Democrat', 'Republican', 'Third'],
['Democrat', 'Republican', 'Third'],
['Democrat', 'Third', 'Republican'],
['Democrat', 'Third', 'Republican'],
['Democrat', 'Third', 'Republican'],
['Democrat', 'Third', 'Republican'],
]
)
But I just want to be able to condense this. It's obviously not manageable to make large datasets this way!
Thank you
Use np.repeat()
:
voters = np.array([['row1', 'row1', 'row1'],
['row2', 'row2', 'row2']])
# We repeat 2 times the first row and 4 times the second row.
np.repeat(voters,[2,4],axis=0)
# voters.repeat([2,4],axis=0) produce the same result.
And we obtain:
array([['row1', 'row1', 'row1'],
['row1', 'row1', 'row1'],
['row2', 'row2', 'row2'],
['row2', 'row2', 'row2'],
['row2', 'row2', 'row2'],
['row2', 'row2', 'row2']])
You can use this:
np.array([['Democrat', 'Republican', 'Third']]* 10000)
to generate as many duplicate rows as you want.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.