How to transform a 2d array in to two different 1d array in python
Question:
I’m trying to transform one 2d array:
{4: 6, 6: 2, 1: 2, 3: 7, 5: 4, 9: 1, 2: 3, 7: 2, 8: 1}
in to 2 different 1d arrays, like this:
arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr2 = [2, 3, 7, 6, 4, 2, 2, 1, 1]
To plot, using matplotlib, arr1 as y and arr2 as x.
How can I do this?
PS: Sorry for the bad English. (;
Answers:
here is what you can do:
import matplotlib.pylab as plt
d = {4: 6, 6: 2, 1: 2, 3: 7, 5: 4, 9: 1, 2: 3, 7: 2, 8: 1}
sorted_list = sorted(d.items()) # sorted by key, return a list of tuples
x, y = zip(*sorted_list) # unpack a list of pairs into two tuples
plt.plot(x, y)
plt.show()
output :
You can use dict.items
and zip
:
d = {4: 6, 6: 2, 1: 2, 3: 7, 5: 4, 9: 1, 2: 3, 7: 2, 8: 1}
arr1, arr2 = map(list, zip(*d.items()))
output:
arr1
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr2
# [2, 3, 7, 6, 4, 2, 2, 1, 1]
A convenience, if you want to plot, might be to use pandas.Series
:
import pandas as pd
pd.Series(d).sort_index().plot()
# or
# import matplotlib .pyplot as plt
# plt.plot(pd.Series(d).sort_index())
output:
I’m trying to transform one 2d array:
{4: 6, 6: 2, 1: 2, 3: 7, 5: 4, 9: 1, 2: 3, 7: 2, 8: 1}
in to 2 different 1d arrays, like this:
arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr2 = [2, 3, 7, 6, 4, 2, 2, 1, 1]
To plot, using matplotlib, arr1 as y and arr2 as x.
How can I do this?
PS: Sorry for the bad English. (;
here is what you can do:
import matplotlib.pylab as plt
d = {4: 6, 6: 2, 1: 2, 3: 7, 5: 4, 9: 1, 2: 3, 7: 2, 8: 1}
sorted_list = sorted(d.items()) # sorted by key, return a list of tuples
x, y = zip(*sorted_list) # unpack a list of pairs into two tuples
plt.plot(x, y)
plt.show()
output :
You can use dict.items
and zip
:
d = {4: 6, 6: 2, 1: 2, 3: 7, 5: 4, 9: 1, 2: 3, 7: 2, 8: 1}
arr1, arr2 = map(list, zip(*d.items()))
output:
arr1
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr2
# [2, 3, 7, 6, 4, 2, 2, 1, 1]
A convenience, if you want to plot, might be to use pandas.Series
:
import pandas as pd
pd.Series(d).sort_index().plot()
# or
# import matplotlib .pyplot as plt
# plt.plot(pd.Series(d).sort_index())
output: