I have a list that contains 8634 values that are either 0, 1, 2, 3 or 4. I want to create a dictionary that also has 8634 key-value pairs that are based on the value in the list. For example, while traversing through the list, if it finds a zero then the key-value pair should be 0:Zero and so fourth until it reaches the end of the list.
Here is my code:
JavaScript
x
12
12
1
for i in label_list:
2
if i == 0:
3
dict.update({i:"Zero"})
4
elif i == 1:
5
dict.update({i:"One"})
6
elif i == 2:
7
dict.update({i:"Two"})
8
elif i == 3:
9
dict.update({i:"Three"})
10
else:
11
dict.update({i:"Four"})
12
The current code only produces 5 Key-Value pairs. My intention is to create a dataframe out of the result.
Advertisement
Answer
Since you are looking to make a dataframe, you can can use pandas map()
with a dictionary that maps numbers to words. For example:
JavaScript
1
15
15
1
import pandas as pd
2
3
words = {
4
0: 'zero',
5
1: 'one',
6
2: 'two',
7
3: 'three',
8
4: 'four'
9
}
10
11
l = [0, 2, 3, 1, 4, 0, 1, 2]
12
13
nums = pd.Series(l)
14
pd.DataFrame({'n': nums, 'words':nums.map(words)})
15
Which creates the dataframe:
JavaScript
1
10
10
1
n words
2
0 0 zero
3
1 2 two
4
2 3 three
5
3 1 one
6
4 4 four
7
5 0 zero
8
6 1 one
9
7 2 two
10