数据帧(DataFrame)是二维数据结构,即数据以行和列的表格方式排列。

数据帧(DataFrame)的功能特点:

  • 潜在的列是不同的类型
  • 大小可变
  • 标记轴(行和列)
  • 可以对行和列执行算术运算

结构体

假设要创建一个包含学生数据的数据帧。参考以下图示 -

可以将上图表视为SQL表或电子表格数据表示。

pandas.DataFrame

pandas中的DataFrame可以使用以下构造函数创建 -


pandas.DataFrame( data, index, columns, dtype, copy)

参数 描述
data 数据采取各种形式,如:ndarrayseriesmaplistsdictconstant和另一个DataFrame
index 对于行标签,要用于结果帧的索引是可选缺省值np.arrange(n),如果没有传递索引值。
columns 对于列标签,可选的默认语法是 - np.arange(n)。 这只有在没有索引传递的情况下才是这样。
dtype 每列的数据类型。
copy 如果默认值为False,则此命令(或任何它)用于复制数据。

创建DataFrame

Pandas数据帧(DataFrame)可以使用各种输入创建,如 -

  • 列表
  • 字典
  • 系列
  • Numpy ndarrays
  • 另一个数据帧(DataFrame)

在本章的后续章节中,我们将看到如何使用这些输入创建数据帧(DataFrame)。

创建一个空的DataFrame

创建基本数据帧是空数据帧。

import pandas as pd

df = pd.DataFrame()
print(df)

输出结果:

Empty DataFrame
Columns: []
Index: []
 

从列表创建DataFrame

  可以使用单个列表或列表列表创建数据帧(DataFrame)。

实例-1


import pandas as pd

data = [1,2,3,4,5]
df = pd.DataFrame(data)
print(df)

输出结果:


1
2
3
4
5
 

实例-2


import pandas as pd

data = [['Alex',10],['Bob',12],['Clarke',13]]
df = pd.DataFrame(data,columns=['Name','Age'])
print(df)

输出结果:

      Name      Age
0 Alex 10
Bob 12
Clarke 13
 

实例-3


import pandas as pd

data = [['Alex',10],['Bob',12],['Clarke',13]]
df = pd.DataFrame(data,columns=['Name','Age'],dtype=float)
print(df)

输出结果:

      Name     Age
0 Alex 10.0
1 Bob 12.0
2 Clarke 13.0
 

注意 - 可以观察到,dtype参数将Age列的类型更改为浮点。

从ndarrays/Lists的字典来创建DataFrame

所有的ndarrays必须具有相同的长度。如果传递了索引(index),则索引的长度应等于数组的长度。

如果没有传递索引,则默认情况下,索引将为range(n),其中n为数组长度。

实例-1

import pandas as pd

data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data)
print(df)

输出结果:

      Age      Name
0 28 Tom
1 34 Jack
2 29 Steve
3 42 Ricky
 

注 - 观察值0,1,2,3。它们是分配给每个使用函数range(n)的默认索引。

示例-2

使用数组创建一个索引的数据帧(DataFrame)。

import pandas as pd

data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data, index=['rank1','rank2','rank3','rank4'])
print(df)

输出结果:

         Age    Name
rank1 28 Tom
rank2 34 Jack
rank3 29 Steve
rank4 42 Ricky
 

注意 - index参数为每行分配一个索引。

从字典列表创建数据帧DataFrame

字典列表可作为输入数据,用来创建数据帧(DataFrame),字典键默认为列名。

实例-1

以下示例显示如何通过传递字典列表来创建数据帧(DataFrame)。

import pandas as pd

data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]
df = pd.DataFrame(data)
print(df)

输出结果:

    a    b      c
0 1 2 NaN
1 5 10 20.0
 

注意 - 观察到,NaN(不是数字)被附加在缺失的区域。

示例-2

以下示例显示如何通过传递字典列表和行索引来创建数据帧(DataFrame)。

import pandas as pd

data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]
df = pd.DataFrame(data, index=['first', 'second'])
print(df)

输出结果:

        a   b       c
first 1 2 NaN
second 5 10 20.0

实例-3

以下示例显示如何使用字典,行索引和列索引列表创建数据帧(DataFrame)。

import pandas as pd

data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]

#With two column indices, values same as dictionary keys
df1 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b']) #With two column indices with one index with other name
df2 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b1'])
print(df1)
print('\n') print(df2)

输出结果:

         a  b
first 1 2
second 5 10 a b1
first 1 NaN
second 5 NaN
 

注意 - 观察,df2使用字典键以外的列索引创建DataFrame; 因此,附加了NaN到位置上。 而df1是使用列索引创建的,与字典键相同,所以也附加了NaN。

从系列的字典来创建DataFrame

字典的系列可以传递以形成一个DataFrame。 所得到的索引是所有系列索引的并集。

示例

import pandas as pd

d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])} df = pd.DataFrame(d)
print(df)

输出结果:

      one    two
a 1.0 1
b 2.0 2
c 3.0 3
d NaN 4
 

注意 - 对于第一个系列,观察到没有传递标签'd',但在结果中,对于d标签,附加了NaN。

列选择,添加和删除。

列选择

  通过列名,来选择列

import pandas as pd

d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])} df = pd.DataFrame(d)
print(df ['one'])

输出结果:

a     1.0
b 2.0
c 3.0
d NaN
Name: one, dtype: float64
 

列添加

  像字典赋值一样直接添加。

import pandas as pd

d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])} df = pd.DataFrame(d) # Adding a new column to an existing DataFrame object with column label by passing new series print ("Adding a new column by passing as Series:")
df['three']=pd.Series([10,20,30],index=['a','b','c'])
print(df)
print('\n') print ("Adding a new column using the existing columns in DataFrame:")
df['four']=df['one']+df['three']
print(df)

输出结果:

Adding a new column by passing as Series:
one two three
a 1.0 1 10.0
b 2.0 2 20.0
c 3.0 3 30.0
d NaN 4 NaN Adding a new column using the existing columns in DataFrame:
one two three four
a 1.0 1 10.0 11.0
b 2.0 2 20.0 22.0
c 3.0 3 30.0 33.0
d NaN 4 NaN NaN
 

列删除

列可以删除或弹出;

import pandas as pd

d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd']),
'three' : pd.Series([10,20,30], index=['a','b','c'])} df = pd.DataFrame(d)
print ("Our dataframe is:")
print(df)
print('\n') # using del function
print ("Deleting the first column using DEL function:")
del df['one']
print(df)
print('\n') # using pop function
print ("Deleting column using POP function:")
df.pop('two')
print(df)

输出结果 -

Our dataframe is:
one three two
a 1.0 10.0 1
b 2.0 20.0 2
c 3.0 30.0 3
d NaN NaN 4 Deleting the first column using DEL function:
three two
a 10.0 1
b 20.0 2
c 30.0 3
d NaN 4 Deleting column using POP function:
three
a 10.0
b 20.0
c 30.0
d NaN
 

行选择,添加和删除

行选择

标签选择

可以通过将行标签传递给loc()函数来选择行。参考以下示例代码 -

import pandas as pd

d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])} df = pd.DataFrame(d)
print(df.loc['b'])

输出结果:

one 2.0
two 2.0
Name: b, dtype: float64

结果是一系列标签作为DataFrame的列名称。 而且,系列的名称是检索的标签。

按整数位置选择

可以通过将整数位置传递给iloc()函数来选择行。参考以下示例代码 -

import pandas as pd

d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])} df = pd.DataFrame(d)
print(df.iloc[])

输出结果:

one   3.0
two 3.0
Name: c, dtype: float64

行切片

可以使用:运算符选择多行。参考以下示例代码 -

import pandas as pd

d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])} df = pd.DataFrame(d)
print(df[2:4])

输出结果:

      one    two
c 3.0 3
d NaN 4
 

附加行

使用append()函数将新行添加到DataFrame。 此功能将附加行结束。

import pandas as pd

df = pd.DataFrame([[1, 2], [3, 4]], columns = ['a','b'])
df2 = pd.DataFrame([[5, 6], [7, 8]], columns = ['a','b']) df = df.append(df2)
print(df)

输出结果:

   a  b
0 1 2
1 3 4
0 5 6
1 7 8
 

删除行

使用索引标签从DataFrame中删除或删除行。 如果标签重复,则会删除多行。

import pandas as pd

df = pd.DataFrame([[1, 2], [3, 4]], columns = ['a','b'])
print(df)
print('\n') df2 = pd.DataFrame([[5, 6], [7, 8]], columns = ['a','b'])
print(df2)
print('\n') df = df.append(df2)
print(df)
print('\n') # Drop rows with label 0
df = df.drop(0)
print(df)

输出结果:

a   b
0  1   2
1  3   4

a    b
0   5    6
1   7   8

   a   b
   1   2
1   3   4
0   5   6
1   7   8

   a   b
1   3   4
1   7   8

 

在上面的例子中,一共有两行被删除,因为这两行包含相同的标签0

 

Pandas | 03 DataFrame 数据帧的更多相关文章

  1. [Pandas] 03 - DataFrame

    DataFrame 表格基本操作 初始化 一并设置 index & columns 类似于倒排表,column相当于words. index就是doc id. df = pd.DataFram ...

  2. python 数据处理学习pandas之DataFrame

    请原谅没有一次写完,本文是自己学习过程中的记录,完善pandas的学习知识,对于现有网上资料的缺少和利用python进行数据分析这本书部分知识的过时,只好以记录的形势来写这篇文章.最如果后续工作定下来 ...

  3. Pandas之Dataframe叠加,排序,统计,重新设置索引

    Pandas之Dataframe索引,排序,统计,重新设置索引 一:叠加 import pandas as pd a_list = [df1,df2,df3] add_data = pd.concat ...

  4. pandas中DataFrame对象to_csv()方法中的encoding参数

    当使用pd.read_csv()方法读取csv格式文件的时候,常常会因为csv文件中带有中文字符而产生字符编码错误,造成读取文件错误,在这个时候,我们可以尝试将pd.read_csv()函数的enco ...

  5. Python3 Pandas的DataFrame数据的增、删、改、查

    Python3 Pandas的DataFrame数据的增.删.改.查 一.DataFrame数据准备 增.删.改.查的方法有很多很多种,这里只展示出常用的几种. 参数inplace默认为False,只 ...

  6. Python3 Pandas的DataFrame格式数据写入excle文件、json、html、剪贴板、数据库

    Python3 Pandas的DataFrame格式数据写入excle文件.json.html.剪贴板.数据库 一.DataFrame格式数据 Pandas是Python下一个开源数据分析的库,它提供 ...

  7. python. pandas(series,dataframe,index) method test

    python. pandas(series,dataframe,index,reindex,csv file read and write) method test import pandas as ...

  8. pandas取dataframe特定行/列

    1. 按列取.按索引/行取.按特定行列取 import numpy as np from pandas import DataFrame import pandas as pd df=DataFram ...

  9. Pandas中DataFrame修改列名

    Pandas中DataFrame修改列名:使用 rename df = pd.read_csv('I:/Papers/consumer/codeandpaper/TmallData/result01- ...

随机推荐

  1. windows上MongoDB远程访问配置

    今天用另一台机器上的MongoDB,但是使用本地连接时,没问题 换成IP地址时,出现 解决的方法,修改配置文件 systemLog: destination: file path: d:/Mongod ...

  2. 版本分支管理标准 - Git Flow

    最近好多开发人员在问如何使用 GIT 进行代码的版本管理. 这里转发一个标准的分支版本控制图. 相关的详细介绍,可以看: <引入git flow分支管理> <非常清晰明了的GIT版本 ...

  3. thinkphp的普通查询与表达式查询

    一.普通查询方式 a.字符串:$arr=$m->where("sex=0 and username='gege'")->find();//字符串需要加引号 b.数组 $ ...

  4. Redis学习之ziplist压缩列表源码分析

    一.压缩列表ziplist在redis中的应用 1.做列表键 当一个列表键只包含少量列表项,并且每个列表项要么是小整数,要么是短字符串,那么redis会使用压缩列表作为列表键的底层实现 2.哈希键 当 ...

  5. c#页面重定向,Server.Transfer 和 Response.Redirect

    Server.Transfer() 重定向发生在服务器端,把处理的控制权从当前页面转移到另一个页面,在转移的工程中没有离开服务器内部控件(如request,session等)保存的信息不变. 1.只能 ...

  6. 我为什么学习Haskell

    说起来,Haskell真是相当冷门而小众的一门语言.在我工作第一年的时候,我平时从网络的一些学习资料上时不时看到有人提到这门语言.那时候的认识就是除了我们平时用的“面向对象语言 (OOP: Objec ...

  7. Python笔记:装饰器

    装饰器        1.特点:装饰器的作用就是为已存在的对象添加额外的功能,特点在于不用改变原先的代码即可扩展功能: 2.使用:装饰器其实也是一个函数,加上@符号后放在另一个函数“头上”就实现了装饰 ...

  8. php中,5行代码实现无限级分类

    <?php /** * 此方法由@Tonton 提供 * http://my.oschina.net/u/918697 * @date 2012-12-12 */function genTree ...

  9. Math基础使用

    /* java.lang.Math类是数学相关的工具类,里面提供的大量静态方法,完成与数学运算的操作 public static double abs(double num):获取绝对值. publi ...

  10. 内部类不能有静态变量(除静态的对Static的理解)

    关于内部类(static与final) Static 不用实例化就能加载进内存 而内部类需要外部类实例化后才能加载进内存.这就间接造成static需要实例化了.与static不需要实例化语义矛盾 1. ...