Pandas | 03 DataFrame 数据帧
数据帧(DataFrame)是二维数据结构,即数据以行和列的表格方式排列。
数据帧(DataFrame)的功能特点:
- 潜在的列是不同的类型
- 大小可变
- 标记轴(行和列)
- 可以对行和列执行算术运算
结构体
假设要创建一个包含学生数据的数据帧。参考以下图示 -

可以将上图表视为SQL表或电子表格数据表示。
pandas.DataFrame
pandas中的DataFrame可以使用以下构造函数创建 -
pandas.DataFrame( data, index, columns, dtype, copy)
| 参数 | 描述 |
|---|---|
data |
数据采取各种形式,如:ndarray,series,map,lists,dict,constant和另一个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 数据帧的更多相关文章
- [Pandas] 03 - DataFrame
DataFrame 表格基本操作 初始化 一并设置 index & columns 类似于倒排表,column相当于words. index就是doc id. df = pd.DataFram ...
- python 数据处理学习pandas之DataFrame
请原谅没有一次写完,本文是自己学习过程中的记录,完善pandas的学习知识,对于现有网上资料的缺少和利用python进行数据分析这本书部分知识的过时,只好以记录的形势来写这篇文章.最如果后续工作定下来 ...
- Pandas之Dataframe叠加,排序,统计,重新设置索引
Pandas之Dataframe索引,排序,统计,重新设置索引 一:叠加 import pandas as pd a_list = [df1,df2,df3] add_data = pd.concat ...
- pandas中DataFrame对象to_csv()方法中的encoding参数
当使用pd.read_csv()方法读取csv格式文件的时候,常常会因为csv文件中带有中文字符而产生字符编码错误,造成读取文件错误,在这个时候,我们可以尝试将pd.read_csv()函数的enco ...
- Python3 Pandas的DataFrame数据的增、删、改、查
Python3 Pandas的DataFrame数据的增.删.改.查 一.DataFrame数据准备 增.删.改.查的方法有很多很多种,这里只展示出常用的几种. 参数inplace默认为False,只 ...
- Python3 Pandas的DataFrame格式数据写入excle文件、json、html、剪贴板、数据库
Python3 Pandas的DataFrame格式数据写入excle文件.json.html.剪贴板.数据库 一.DataFrame格式数据 Pandas是Python下一个开源数据分析的库,它提供 ...
- python. pandas(series,dataframe,index) method test
python. pandas(series,dataframe,index,reindex,csv file read and write) method test import pandas as ...
- pandas取dataframe特定行/列
1. 按列取.按索引/行取.按特定行列取 import numpy as np from pandas import DataFrame import pandas as pd df=DataFram ...
- Pandas中DataFrame修改列名
Pandas中DataFrame修改列名:使用 rename df = pd.read_csv('I:/Papers/consumer/codeandpaper/TmallData/result01- ...
随机推荐
- CentOS7 Hadoop 安装(完全分布式)
一.hadoop集群安装模式 单机模式 直接解压,无需任何配置.主要用于测试代码.没有分布式文件系统. 伪分布式 完全分布式的一种形式,只是所有的进程都配置要一个节点上.有分布式文件系统,只不 ...
- Python之threading多线程,多进程
1.threading模块是Python里面常用的线程模块,多线程处理任务对于提升效率非常重要,先说一下线程和进程的各种区别,如图 概括起来就是 IO密集型(不用CPU) 多线程计算密集型(用CPU) ...
- git 版本(commit) 回退 -- 使用git reset 指令
刚刚提交了三个commit, git reflog显示如下: 最后一个commit在文件末尾加了一行:v3,以此类推: 下面,使用git reset --hard commitID来进行commit回 ...
- Rider中Winform开发支持预览(5)
1.Rider .netCore3.0 winform设计器支持预览,这点vs目前还不支持. 2.不过winform下控件选择工具栏都是没有图标的
- Centos 7搭建Gitlab服务器超详细Centos 7搭建Gitlab服务器超详细(搭建成功)
一. 安装并配置必要的依赖关系在CentOS系统上安装所需的依赖:ssh,防火墙,postfix(用于邮件通知) ,wget,以下这些命令也会打开系统防火墙中的HTTP和SSH端口访问. 注意:用户不 ...
- 【模板整合计划】DP动态规划
[模板整合计划]DP动态规划 一:[背包] 1.[01背包] 采药 \([P1048]\) #include<algorithm> #include<cstdio> int T ...
- Centos 7.6 安装 oracle 10.2.0.1 数据库软件
step 1: 编辑 /etc/redhat-release :内容为redhat-4 step 2: 安装32位的软件包:yum install libXp.i686 libXt.i686 li ...
- PIE SDK主成分变换
1.算法功能简介 主成分变换(Principal Component Analysis,PCA)又称K-L(Karhunen-Loeve)变换或霍特林(Hotelling)变换,是基于变量之间的相 ...
- ALBERT+BiLSTM+CRF实现序列标注
一.模型框架图 二.分层介绍 1)ALBERT层 albert是以单个汉字作为输入的(本次配置最大为128个,短句做padding),两边分别加上开始标识CLS和结束标识SEP,输出的是每个输入wor ...
- 15-213 Bomb Lab
bomb lab是一道学习汇编语言的题,一共有六个阶段,全部解开即可完成 phase_1 0x0000000000400e32 <+>: callq 0x40149e <read_l ...