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:
for i in label_list:
if i == 0:
dict.update({i:"Zero"})
elif i == 1:
dict.update({i:"One"})
elif i == 2:
dict.update({i:"Two"})
elif i == 3:
dict.update({i:"Three"})
else:
dict.update({i:"Four"})
The current code only produces 5 Key-Value pairs. My intention is to create a dataframe out of the result.
CodePudding user response:
Since you are looking to make a dataframe, you can can use pandas map() with a dictionary that maps numbers to words. For example:
import pandas as pd
words = {
0: 'zero',
1: 'one',
2: 'two',
3: 'three',
4: 'four'
}
l = [0, 2, 3, 1, 4, 0, 1, 2]
nums = pd.Series(l)
pd.DataFrame({'n': nums, 'words':nums.map(words)})
Which creates the dataframe:
n words
0 0 zero
1 2 two
2 3 three
3 1 one
4 4 four
5 0 zero
6 1 one
7 2 two
CodePudding user response:
Dictionaries can hold exactly one instance of a key. That's sort of the whole point of them.
If, on the other hand, your goal is to map numbers from zero to 8634 to their English names, then I have good news for you. I wrote and maintain1 a library of random utility routines called haggis, which has a routine haggis.numbers.english that maps integers to their English names:
from haggis.numbers import english
...
numbers = {i: english(i) for i in range(len(label_list))}
1I've been a bit lax about uploading to pypi, so if you want to use the library, I'd recommend cloning from GitHub and running python setup.py install.
CodePudding user response:
Your for loop should be for i in range(len(label_list)):. Since your list only contains 0, 1, 2, 3, 4, the only values i can take on with your current program can only be 0, 1, 2, 3, 4.
