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.
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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments