为什么我们需要将压缩对象转换为列表

Sho*_*anz 4 python pandas

我正在尝试完成一个数据营练习,其中我需要将 2 个列表转换为 a zip object,然后转换为 a dict,最后dataframe使用 pandas 进行转换。

但是,如果我zip()在列表上使用函数并将它们转换为字典,然后转换为数据帧,我不会得到任何错误,但会得到一个看起来完美的数据帧。但说明说我必须首先将压缩对象转换为列表,然后将其转换为dict().

我不明白这对我有什么帮助,因为我每次都得到相同的输出。即数据框。
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)
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

没有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)
Run Code Online (Sandbox Code Playgroud)

output:

<zip object at 0x10c069648>
          Country  Total
0   United States   1118
1    Soviet Union    473
2  United Kingdom    273
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 5

我认为dict(zipped)转换zip objectlist objectdictionary。所以这里转换为list是多余的。


DataFrame但如果想从zip其中的对象创建是有问题的,需要首先python 3转换为lists of s:tuple

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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)