为什么我们需要将压缩的对象转换为列表 [英] Why do we need to convert a zipped object into a list

查看:99
本文介绍了为什么我们需要将压缩的对象转换为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试完成一个数据营练习,其中需要将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 objectlist 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是有问题的,则需要先转换为tuplelist s:

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

这篇关于为什么我们需要将压缩的对象转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆