I have this toy dataset:
cat count class_weight
cars 17824 0.000404
bus 124784 0.000553
planes 111271 0.000620
I want to output a dictionary
with index and class_weight values, like this:
{0: 0.000404,
1: 0.000553,
2: 0.000620}
I am doing:
class_weight = {}
for index, label in enumerate(categories):
class_weight[index] = df[df['cat'] == categories]['class_weight'].values[0]
categories
is a numpy.ndarray
with the cat
values
and my output is wrong because the values[0
is returning the first value for all car items:
{0: 0.000404,
1: 0.000404,
2: 0.000404}
How can I fix it?
CodePudding user response:
pd.Series.to_dict
's default output is what you're looking for.
Given:
cat count class_weight
0 cars 17824 0.000404
1 bus 124784 0.000553
2 planes 111271 0.000620
Doing:
x = df.class_weight.to_dict()
print(x)
Output:
{
0: 0.000404,
1: 0.000553,
2: 0.00062
}