首页 > 编程知识 正文

如何用 Python 创建数据帧

时间:2023-11-25 15:30:09 阅读:309169 作者:LRUY

数据帧是数据的二维集合。这是一种数据结构,其中数据以表格形式存储。数据集按行和列排列;我们可以在数据帧中存储多个数据集。我们可以执行各种算术运算,例如在数据帧中添加列/行选择和列/行。

我们可以从外部存储器导入数据帧;这些存储可以称为 SQL 数据库、CSV 文件和 Excel 文件。我们也可以使用列表、字典、以及来自列表的字典等。

在本教程中,我们将学习以多种方式创建数据帧。让我们理解这些不同的方式。

首先,我们需要将Pandas库安装到 Python 环境中。

空数据帧

我们可以创建一个基本的空数据帧。需要调用 dataframe 构造器来创建 DataFrame。让我们理解下面的例子。

示例-


# import pandas as pd
import pandas as pd

# Calling DataFrame constructor
df = pd.DataFrame()

print(df)

输出:

Empty DataFrame
Columns: []
Index: []

方法 2:使用列表创建数据帧

我们可以使用单个列表或列表列表来创建数据帧。让我们理解下面的例子。

示例-


# importing pandas library
import pandas as pd

# string values in the list 
lst = ['Java', 'Python', 'C', 'C++',
         'JavaScript', 'Swift', 'Go']

# Calling DataFrame constructor on list
dframe = pd.DataFrame(lst)
print(dframe)

输出:

0        Java
1      Python
2           C
3         C++
4   JavaScript
5       Swift
6          Go

方法 3:从一组数据/列表中创建数据帧

数组/列表的字典可用于创建数据帧,所有的数组必须具有相同的长度。默认情况下,索引将是一个范围(n);其中 n 表示阵列长度。让我们理解下面的例子。

示例-


import pandas as pd

# assign data of lists.
data = {'Name': ['Tom', 'Joseph', 'Krish', 'John'], 'Age': [20, 21, 19, 18]}

# Create DataFrame
df = pd.DataFrame(data)

# Print the output.
print(df)

输出:

     Name  Age
0     Tom   20
1  Joseph   21
2   Krish   19
3    John   18

方法 4:使用数组创建索引数据帧

让我们理解以下使用数组创建索引数据帧的示例。

示例-


# DataFrame using arrays.
import pandas as pd

# assign data of lists.
data = {'Name':['Renault', 'Duster', 'Maruti', 'Honda City'], 'Ratings':[9.0, 8.0, 5.0, 3.0]}

# Creates pandas DataFrame.
df = pd.DataFrame(data, index =['position1', 'position2', 'position3', 'position4'])

# print the data
print(df)

输出:

               Name      Ratings
position1     Renault      9.0
position2      Duster      8.0
position3      Maruti      5.0
position4    Honda City      3.0

解释-

在上面的代码中,我们已经用各种汽车名称及其等级定义了列名。我们使用数组来创建索引。

方法 5:从字典列表中创建数据帧

我们可以将字典列表作为输入数据来创建 Pandas 数据帧。默认情况下,列名被视为键。让我们理解下面的例子。

示例-


# the example is to create
# Pandas DataFrame by lists of dicts.
import pandas as pd

# assign values to lists.
data = [{'A': 10, 'B': 20, 'C':30}, {'x':100, 'y': 200, 'z': 300}]

# Creates DataFrame.
df = pd.DataFrame(data)

# Print the data
print(df)

输出:

    A      B      C      x      y      z
0  10.0  20.0  30.0    NaN    NaN    NaN
1   NaN   NaN   NaN  100.0  200.0  300.0

让我们来理解另一个例子,用行索引和列索引从字典列表中创建 pandas dataframe。

示例- 2:


import pandas as pd

# assigns values to lists.
data = [{'x': 1, 'y': 2}, {'A': 15, 'B': 17, 'C': 19}]

# With two column indices, values same
# as dictionary keys
dframe1 = pd.DataFrame(data, index =['first', 'second'], columns =['x', 'y'])

# With two column indices with
# one index with other name
dframe2 = pd.DataFrame(data, index =['first', 'second'], columns =['x', 'y1'])

# print the first data frame
print (dframe1, "n")
# Print the second DataFrame.
print (dframe2)

输出:

             x    y
first   1.0   2.0
second  NaN NaN 

             x    y1
first   1.0 NaN
second NaN NaN

让我们理解另一个通过传递字典和行的列表来创建数据帧的例子。

示例- 3


# The example is to create
# Pandas DataFrame by passing lists of
# Dictionaries and row indices.
import pandas as pd

# assign values to lists
data = [{'x': 2, 'z':3}, {'x': 10, 'y': 20, 'z': 30}]

# Creates padas DataFrame by passing
# Lists of dictionaries and row index.
dframe = pd.DataFrame(data, index =['first', 'second'])

# Print the dataframe
print(dframe)

输出:

         x     y   z
first    2   NaN   3
second  10  20.0  30

我们已经讨论了使用字典列表创建数据帧的三种方法。

方法 6:使用 zip()函数创建数据帧

zip()函数用于合并两个列表。让我们理解下面的例子。

示例-


# The example is to create
# pandas dataframe from lists using zip.

import pandas as pd

# List1
Name = ['tom', 'krish', 'arun', 'juli']

# List2
Marks = [95, 63, 54, 47]

#  two lists.
# and merge them by using zip().
list_tuples = list(zip(Name, Marks))

# Assign data to tuples.
print(list_tuples)

# Converting lists of tuples into
# pandas Dataframe.
dframe = pd.DataFrame(list_tuples, columns=['Name', 'Marks'])

# Print data.
print(dframe)

输出:

[('john', 95), ('krish', 63), ('arun', 54), ('juli', 47)]
    Name  Marks
0   john     95
1  krish     63
2   arun     54
3   juli     47

方法 7:从系列字典创建数据帧

可以传递字典来创建数据帧。我们可以使用系列的 Dicts,其中后续的索引是传递的索引值的所有系列的并集。让我们理解下面的例子。

示例-


# Pandas Dataframe from Dicts of series.

import pandas as pd

# Initialize data to Dicts of series.
d = {'Electronics' : pd.Series([97, 56, 87, 45], index =['John', 'Abhinay', 'Peter', 'Andrew']),
   'Civil' : pd.Series([97, 88, 44, 96], index =['John', 'Abhinay', 'Peter', 'Andrew'])}

# creates Dataframe.
dframe = pd.DataFrame(d)

# print the data.
print(dframe)

输出:

        Electronics      Civil
John             97        97
Abhinay      56        88
Peter           87        44
Andrew      45        96

在本教程中,我们讨论了创建数据帧的不同方法。


版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。