首页 文章资讯内容详情

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

2026-06-02 4 花语

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

PandasDataFrame对象将以表格格式存储数据,这里列表对象的元组元素将成为结果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对象。

为列参数提供了一个字符列表,它将这些字符分配为结果数据帧的列标签。

输出结果

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)

解释

在以下示例中,我们使用元组列表创建了一个简单的PandasDataFrame对象,每个元组都有一个字符和一个整数值。

输出结果

Char Ord 0 A 65 1 B 66 2 C 67

输出DataFrame是使用上面块中的元组列表创建的,列标签是Char,Ord,数据取自元组元素。