如何使用元组列表创建pandas DataFrame?


pandas DataFrame 构造函数将使用 Python 的元组列表创建一个 pandas DataFrame 对象。我们需要将此元组列表作为参数发送到 pandas.DataFrame() 函数。

Pandas DataFrame 对象将以表格形式存储数据,这里列表对象的元组元素将成为结果 DataFrame 的行。

示例

# importing the pandas package
import pandas as pd

# creating a list of tuples
list_of_tuples = [(11,22,33),(10,20,30),(101,202,303)]

# creating DataFrame
df = pd.DataFrame(list_of_tuples, columns= ['A','B','C'])

# displaying resultant DataFrame
print(df)

解释

在上面的示例中,我们有一个包含 3 个元组元素的列表,每个元组又包含 3 个整数元素,我们将此列表对象作为数据传递给 DataFrame 构造函数。然后它将创建一个具有 3 行 3 列的 DataFrame 对象。

一个字符列表被赋给 columns 参数,它将把这些字符作为结果 DataFrame 的列标签。

输出

      A     B    C
0    11    22    33
1    10    20    30
2   101   202   303

在上面的输出块中可以看到结果 DataFrame 对象,它有 3 行 3 列,列标签表示为 A、B、C。

示例

# importing the pandas package
import pandas as pd

# creating a list of tuples
list_of_tuples = [('A',65),('B',66),('C',67)]

# creating DataFrame
df = pd.DataFrame(list_of_tuples, columns=['Char', 'Ord'])

# displaying resultant DataFrame
print(df)

解释

在下面的示例中,我们使用元组列表创建了一个简单的 pandas DataFrame 对象,每个元组包含一个字符和一个整数值。

输出

 Char  Ord
0   A   65
1   B   66
2   C   67

上面的代码块使用元组列表创建了输出 DataFrame,列标签为“Char, Ord”,数据取自元组元素。

更新于:2021年11月17日

3K+ 浏览量

启动您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.