im trying to convert a data dictionary with a structure as below:
{'name': array(['Ben','Sean,'Fred'])
'age': array([22, 16, 35]),
'marks': array([98, 75, 60]),
'result': array('HD','D','C')}
I need to then filter out the dictionary to only include name, mark and result in the new numpy array to be able to plot on a graph (i can do this but cant for the life of me filter the list and then convert to numpy)
Let's assume your dictionary is something like this.
dict = {
'name': ['Ben','Sean','Fred'],
'age': [22, 16, 35],
'marks': [98, 75, 60],
'result': ['HD','D','C']
}
You can iterate over the dictionary to get desired values and append them into a list. Then convert it into a NumPy array. Here I am using all of the keys
name, age, marks, result
but you can filter some keys if you like.
if key not in ['age']:
import numpy as np
data_list = []
for key, val in dict.items():
data_list.append(val)
numpy_array = np.array(data_list)
transpose = numpy_array.T
transpose_list = transpose.tolist()
The end result will be following:
[['Ben', '22', '98', 'HD'],
['Sean', '16', '75', 'D'],
['Fred', '35', '60', 'C']]
You can try pandas
import pandas as pd
d = {
'name': ['Ben','Sean','Fred'],
'age': [22, 16, 35],
'marks': [98, 75, 60],
'result': ['HD','D','C']
}
df = pd.DataFrame(d)
result = df[['name', 'marks', 'result']].T.values
print(type(result))
print(result)
<class 'numpy.ndarray'>
[['Ben' 'Sean' 'Fred']
[98 75 60]
['HD' 'D' 'C']]
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.