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

标签 python pandas

我正在尝试完成一个数据营练习,其中我需要将 2 个列表转换为 zip object然后进入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)

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对象list对象转换为字典。所以这里转换为list是多余的。

<小时/>

但是如果想从 python 3 中的 zip 对象创建 DataFrame 这是问题,需要转换为 list首先是元组:

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

关于python - 为什么我们需要将压缩对象转换为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49461605/

相关文章:

php - 运行 python 文件并读取输出

python - 如何实现 Nadex 自动交易机器人?

python - 通过解析 json 列创建新列

python - Pandas 在移动的数据帧上滚动

python-3.x - 将 NaN 文本列分离到其他数据框中

python - 从 SQL 表中获取值以及 Python 中的列表形式的列名

python - 读取 Azure Functions 上的 Shapefile

python - 数字作为字符串的 seaborn 色调

python - Pandas:Apply():返回多个值

python - 情节饼上的标签非常接近