pandas基础之Series与DataFrame操作-成都创新互联网站建设

关于创新互联

多方位宣传企业产品与服务 突出企业形象

公司简介 公司的服务 荣誉资质 新闻动态 联系我们

pandas基础之Series与DataFrame操作

pandas包

我们提供的服务有:成都网站建设、成都网站制作、微信公众号开发、网站优化、网站认证、中宁ssl等。为千余家企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的中宁网站制作公司

# 引入包

import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

Series

Series 是一维带标签的数组,数组里可以放任意的数据(整数,浮点数,字符串,Python Object)。其基本的创建函数是:

s = pd.Series(data, index=index)

其中 index 是一个列表,用来作为数据的标签。data 可以是不同的数据类型:

Python 字典

ndarray 对象

一个标量值,如 5

Series创建

s = pd.Series([1,3,5,np.nan,6,8])

Series日期创建

# 生成日期 从2013-01-01 生成至 2013-01-06

dates = pd.date_range('20130101', periods=6)

# DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04','2013-01-05', '2013-01-06'], dtype='datetime64[ns]', freq='D')

Series创建列表

# 生成2列 第一列: 012345678910 第二列: abbcdabacad

s = pd.Series(list('abbcdabacad'))

# 统计不同的列名

s.unique()

# 统计列名出现的次数

s.value_counts()

# 判断第一列是否在列表中

s.isin(['a', 'b', 'c'])

Series索引

# 两列一列abcde 一列5个随机数

s = pd.Series(np.random.rand(5), index=list('abcde'))

# s的列名(第一列),是Index对象

s.index

# 添加一行 alpha

s.index.name = 'alpha'

# 返回所有第一列为'a'的值

s['a']

# 是否有重复的index

s.index.is_unique

# 返回不重复index

s.index.unique()

# 按index分组,求出每组和

s.groupby(s.index).sum()

DataFrame

DataFrame 是二维带行标签和列标签的数组。可以把 DataFrame 想你成一个 Excel 表格或一个 SQL 数据库的表格,还可以相像成是一个 Series 对象字典。它是 Pandas 里最常用的数据结构。

DataFrame创建

df = pd.DataFrame(np.random.randn(4, 6), index=list('ADFH'), columns=['one', 'two', 'three', 'four', 'five', 'six'])

# 添加index 如果该index没有对应值设为NaN

df2 = df.reindex(index=list('ABCDEFGH'))

# 重新设置col(行头)

df.reindex(columns=['one', 'three', 'five', 'seven'])

# 把NaN值设为默认的0

df.reindex(columns=['one', 'three', 'five', 'seven'], fill_value=0)

# fill method 只对行有效

df.reindex(columns=['one', 'three', 'five', 'seven'], method='ffill')

# 重置列index

df.reindex(index=list('ABCDEFGH'), method='ffill')

DataFrame操作

df = pd.DataFrame(np.random.randn(4, 6), index=list('ADFH'), columns=['one', 'two', 'three', 'four', 'five', 'six'])

# 所有index 为'A' col 为'one'的位置的值设置为100

df.loc['A']['one'] = 100

# 舍弃index 为'A'的行

df.drop('A')

# 舍弃columns 为 'two' 'four'的列

df2 = df.drop(['two', 'four'], axis=1)

# 数据拷贝

df.iloc[0, 0] = 100

# 获取index 为'one'的行

df.loc['one']

DataFrame计算

df = pd.DataFrame(np.arange(12).reshape(4, 3), index=['one', 'two', 'three', 'four'], columns=list('ABC'))

# 每一列作为一个 Series 作为参数传递给 lambda 函数

df.apply(lambda x: x.max() - x.min())

# 每一行作为一个 Series 作为参数传递给 lambda 函数

df.apply(lambda x: x.max() - x.min(), axis=1)

# 返回多个值组成的 Series

def min_max(x):郑州人流多少钱 http://mobile.zyyyzz.com/

return pd.Series([x.min(), x.max()], index=['min', 'max'])

df.apply(min_max, axis=1)

# applymap 逐元素计算 每个值保留2位小数

formater = '{0:.02f}'.format

df.applymap(formater)

DataFrame列选择/增加/删除

df = pd.DataFrame(np.random.randn(6, 4), columns=['one', 'two', 'three', 'four'])

# 第三列 为 第一列 加上 第二列

df['three'] = df['one'] + df['two']

# 添加一个flag列 大于0为True 否则为False

df['flag'] = df['one'] > 0

# 删除col为'three'的列

del df['three']

# 获取被删的

four = df.pop('three')

# 选取col为 five

df['five'] = 5

#

df['one_trunc'] = df['one'][:2]

# 指定插入位置

df.insert(1, 'bar', df['one'])

使用assign() 方法来插入新列

df = pd.DataFrame(np.random.randint(1, 5, (6, 4)), columns=list('ABCD'))

# 新列Ratio 值为 df['A'] / df['B']

df.assign(Ratio = df['A'] / df['B'])

# 新列AB_Ratio CD_Ratio 值为lambda表达式的值

df.assign(AB_Ratio = lambda x: x.A / x.B, CD_Ratio = lambda x: x.C - x.D)

DataFrame排序

df = pd.DataFrame(np.random.randint(1, 10, (4, 3)), index=list('ABCD'), columns=['one', 'two', 'three'])

# 按index 为one 排序

df.sort_values(by='one')

#

s.rank()

DataFrame操作

DataFrame 在进行数据计算时,会自动按行和列进行数据对齐。最终的计算结果会合并两个 DataFrame。

df1 = pd.DataFrame(np.random.randn(10, 4), index=list('abcdefghij'), columns=['A', 'B', 'C', 'D'])

df2 = pd.DataFrame(np.random.randn(7, 3), index=list('cdefghi'), columns=['A', 'B', 'C'])

df1 + df2

df1 - df1.iloc[0]


分享标题:pandas基础之Series与DataFrame操作
本文链接:http://kswsj.cn/article/jjcceg.html

其他资讯