Python数据分析——Pandas基础

pandas基础

pandas介绍

Python Data Analysis Library

pandas是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。Pandas 纳入 了大量库和一些标准的数据模型,提供了高效地操作大型结构化数据集所需的工具。

pandas核心数据结构

数据结构是计算机存储、组织数据的方式。 通常情况下,精心选择的数据结构可以带来更高的运行或者存储效率。数据结构往往同高效的检索算法和索引技术有关。

Series

Series可以理解为一个一维的数组,只是index名称可以自己改动。类似于定长的有序字典,有Index和 value。

import pandas as pd
import numpy as np

# 创建一个空的系列
s = pd.Series()
# 从ndarray创建一个系列
data = np.array(['a','b','c','d'])
s = pd.Series(data)
s = pd.Series(data,index=[100,101,102,103])
# 从字典创建一个系列	
data = {
   'a' : 0., 'b' : 1., 'c' : 2.}
s = pd.Series(data)
# 从标量创建一个系列
s = pd.Series(5, index=[0, 1, 2, 3])

访问Series中的数据:

# 使用索引检索元素
s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])
print(s[0], s[:3], s[-3:])
# 使用标签检索数据
print(s['a'], s[['a','c','d']])

pandas日期处理

# pandas识别的日期字符串格式
dates = pd.Series(['2011', '2011-02', '2011-03-01', '2011/04/01', 
                   '2011/05/01 01:01:01', '01 Jun 2011'])
# to_datetime() 转换日期数据类型
dates = pd.to_datetime(dates)
print(dates, dates.dtype, type(dates))
print(dates.dt.day)

# datetime类型数据支持日期运算
delta = dates - pd.to_datetime('1970-01-01')
# 获取天数数值
print(delta.dt.days)

Series.dt提供了很多日期相关操作,如下:

Series.dt.year	The year of the datetime.
Series.dt.month	The month as January=1, December=12.
Series.dt.day	The days of the datetime.
Series.dt.hour	The hours of the datetime.
Series.dt.minute	The minutes of the datetime.
Series.dt.second	The seconds of the datetime.
Series.dt.microsecond	The microseconds of the datetime.
Series.dt.week	The week ordinal of the year.
Series.dt.weekofyear	The week ordinal of the year.
Series.dt.dayofweek	The day of the week with Monday=0, Sunday=6.
Series.dt.weekday	The day of the week with Monday=0, Sunday=6.
Series.dt.dayofyear	The ordinal day of the year.
Series.dt.quarter	The quarter of the date.
Series.dt.is_month_start	Indicates whether the date is the first day of the month.
Series.dt.is_month_end	Indicates whether the date is the last day of the month.
Series.dt.is_quarter_start	Indicator for whether the date is the first day of a quarter.
Series.dt.is_quarter_end	Indicator for whether the date is the last day of a quarter.
Series.dt.is_year_start	Indicate whether the date is the first day of a year.
Series.dt.is_year_end	Indicate whether the date is the last day of the year.
Series.dt.is_leap_year	Boolean indicator if the date belongs to a leap year.
Series.dt.days_in_month	The number of days in the month.
DateTimeIndex

通过指定周期和频率,使用date.range()函数就可以创建日期序列。 默认情况下,范围的频率是天。

import pandas as pd
# 以日为频率
datelist = pd.date_range('2019/08/21', periods=5)
print(datelist)
# 以月为频率
datelist = pd.date_range('2019/08/21', periods=5,freq='M')
print(datelist)
# 构建某个区间的时间序列
start = pd.datetime(2017, 11, 1)
end = pd.datetime(2017, 11, 5)
dates = pd.date_range(start, end)
print(dates)

bdate_range()用来表示商业日期范围,不同于date_range(),它不包括星期六和星期天。

import pandas as pd
datelist = pd.bdate_range('2011/11/03', periods=5)
print(datelist)
DataFrame

DataFrame是一个类似于表格的数据类型,可以理解为一个二维数组,索引有两个维度,可更改。DataFrame具有以下特点:

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

# 创建一个空的DataFrame
df = pd.DataFrame()
print(df)

# 从列表创建DataFrame
data = [1,2,3,4,5]
df = pd.DataFrame(data)
print(df)
data = [['Alex',10],['Bob',12],['Clarke',13]]
df = pd.DataFrame(data,columns=['Name','Age'])
print(df)
data = [['Alex',10],['Bob',12],['Clarke',13]]
df = pd.DataFrame(data,columns=['Name','Age'],dtype=float)
print(df)
data = [{
   'a': 1, 'b': 2},{
   'a': 5, 'b': 10, 'c': 20}]
df = pd.DataFrame(data)
print(df)

# 从字典来创建DataFrame
data = {
   'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data, index=['s1','s2','s3','s4'])
print(df)
data = {
   '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(data)
print(df)
核心数据结构操作

列访问

DataFrame的单列数据为一个Series。根据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'])
print(df
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: Pandas是一个Python库,用于数据处理和分析。在数据分析中,预处理是非常重要的一步,因为它可以帮助我们清洗和转换数据,使其更适合进行分析。Pandas提供了一些强大的预处理功能,包括数据清洗、数据转换、数据重塑和数据合并等。在使用Pandas进行数据分析时,预处理是必不可少的一步。 ### 回答2: 在数据分析中,数据的预处理是一个必要的过程。它的主要目的是清洗数据,准备数据,以便后续分析。在Python中,pandas是一种广泛使用的数据处理库。pandas可以通过其高效的数据结构和操作方法来清洗和处理数据。在本文中,将介绍pandas预处理的一些常见技术。 一、读取数据 在pandas中,使用read_csv()函数读取CSV格式的数据文件,read_excel()函数读取Excel格式的数据文件。它们都有很多选项,可以根据具体文件的格式进行设置。 二、查看数据 在pandas中,使用以下函数来查看数据: 1. head() - 显示数据框的前几行; 2. tail() - 显示数据框的后几行; 3. columns - 显示数据框的列名; 4. shape - 显示数据框的行列数; 5. info() - 显示数据框的基本信息,包括每列的名称、非空值数量和数据类型。 三、数据清洗 在数据清洗中,有以下一些常见的技术: 1. 删除重复行:使用drop_duplicates()函数; 2. 替换空值:使用fillna()函数; 3. 删除空值:使用dropna()函数; 4. 更改数据类型:使用astype()函数。 四、数据准备 在数据准备中,有以下一些常见的技术: 1. 数据合并:使用merge()函数; 2. 数据筛选:使用loc()函数或者iloc()函数; 3. 数据分组:使用groupby()函数; 4. 数据排序:使用sort_values()函数。 五、数据分析数据分析中,有以下一些常见的技术: 1. 数据聚合:使用agg()函数; 2. 统计描述:使用describe()函数; 3. 数据可视化:使用matplotlib或者seaborn库。 综上所述,pandas预处理是数据分析中必不可少的一步。通过使用pandas提供的函数和方法,可以方便地清理和处理数据,使其更容易被分析。 ### 回答3: PandasPython中最强大的数据处理库之一,它提供了DataFrame和Series这两种数据结构,可以快速便捷地处理数据。在数据分析过程中,我们往往需要先对数据进行预处理,以便后续的分析。Pandas提供了一系列的方法和函数,可以帮助我们进行数据的预处理。 首先,在进行数据分析之前,我们需要了解自己所面对的数据类型和数据结构。Pandas中的DataFrame结构就是类似于表格的结构,每一行代表一个样本,每一列代表一个属性。Series则是一维的数组结构。通过pandas.read_csv(),我们可以读取CSV格式的数据,并转化为DataFrame结构。 接下来,我们要对数据进行一些基本的处理,例如数据清洗、数据去重、缺失值处理、异常值处理等。在数据清洗过程中,我们往往需要对数据进行一些特殊的处理,例如字符串的分割、合并、替换等操作,Pandas提供了一系列能够对文本进行操作的函数。在数据去重方面,我们可以使用drop_duplicates()函数,它可以去除DataFrame中的重复记录。在处理缺失值时,Pandas提供了一系列的函数,如fillna()函数、dropna()函数,可以方便地将NaN值变为其他有意义的值,或者删除缺失值的行或列。在异常值处理方面,我们可以使用isoutlier()函数来找到数据中的异常值,并进行处理。 在数据预处理完成后,我们可以对数据进行一些统计分析,例如计算小计、计算总计、分位数、极差、方差、标准差等统计指标。我们可以使用describe()函数来获得数据的统计描述,还可以使用groupby()函数来对数据分组,使用agg()函数对每组进行计算统计指标。此外,我们还可以对数据进行排序、丢弃、合并等操作。 总之,Pandas是一个非常强大的Python库,可以轻松处理数据预处理和数据处理方面的任务。Pandas作为数据分析和数据处理的基础库,使用熟练后可以在数据分析中发挥更大的作用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值