为什么我们需要将压缩的对象转换为列表 [英] Why do we need to convert a zipped object into a list
问题描述
我正在尝试完成一个数据营练习,其中需要将2个列表转换为zip object
,然后转换为dict
,最终使用熊猫获得dataframe
.
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.
但是,如果我在列表上使用zip()
函数并将其转换为dict然后再转换为数据框,则不会出现任何错误,而是简单的外观完美的数据框.
但是说明说我必须先将压缩的对象转换为列表,然后再将其转换为dict()
.
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 am using python3
I dont understand how that helps me because I get the same output each time. i.e a dataframe.
I am using python3
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
推荐答案
我认为dict(zipped)
将zip object
或list object
转换为dictionary
.因此,这里转换为list
是多余的.
I think dict(zipped)
convert zip object
or list object
to dictionary
. So here convert to list
is redundant.
但是如果要从python 3
中的zip
对象创建DataFrame
是有问题的,则需要先转换为tuple
的list
s:
But if want create DataFrame
from zip
object in python 3
it is problem, need convert to list
s of tuple
s 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
这篇关于为什么我们需要将压缩的对象转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!