I am trying to complete a datacamp exercise in which I am required to convert 2 lists into a zip object and then into a dict to finally get a dataframe using pandas.
However, If I use zip() function over the lists and convert them into a dict and then to a dataframe I get no errors but simple a perfect looking dataframe.
But the instructions say that i must convert a zipped object into a list first and then convert it into a dict().
I dont understand how that helps me because I get the same output each time. i.e a dataframe.
I am using python3
list()list_keys = ['Country', 'Total']
list_values = [['United States', 'Soviet Union', 'United Kingdom'], [1118, 473, 273]]
import pandas as pd
zipped = list(zip(list_keys,list_values))
# Inspect the list using print()
print(zipped)
# Build a dictionary with the zipped list: data
data = dict(zipped)
# Build and inspect a DataFrame from the dictionary: df
df = pd.DataFrame(data)
print(df)
output:[('Country', ['United States', 'Soviet Union', 'United Kingdom']), ('Total', [1118, 473, 273])]
Country Total
0 United States 1118
1 Soviet Union 473
2 United Kingdom 273
list()zipped = zip(list_keys,list_values)
# Inspect the list using print()
print(zipped)
# Build a dictionary with the zipped list: data
data = dict(zipped)
# Build and inspect a DataFrame from the dictionary: df
df = pd.DataFrame(data)
print(df)
output:<zip object at 0x10c069648>
Country Total
0 United States 1118
1 Soviet Union 473
2 United Kingdom 273
I think dict(zipped) convert zip object or list object to dictionary. So here convert to list is redundant.
But if want create DataFrame from zip object in python 3 it is problem, need convert to lists of tuples first:
a = ['United States', 'Soviet Union', 'United Kingdom']
b = [1118, 473, 273]
c = ['Country', 'Total']
zipped = zip(a,b)
print(zipped)
<zip object at 0x000000000DC4E8C8>
df = pd.DataFrame(zipped, columns=c)
print(df)
TypeError: data argument can't be an iterator
print(list(zipped))
[('United States', 1118), ('Soviet Union', 473), ('United Kingdom', 273)]
df = pd.DataFrame(list(zipped), columns=c)
print(df)
Country Total
0 United States 1118
1 Soviet Union 473
2 United Kingdom 273
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With