1.Pandas基础,Series,DataFrame

0 引言

Pandas是基于Numpy的一种工具,主要是为了解决数据分析任务,Pandas主要有以下几种数据结构:

  • Series:一维数组,与Numpy中的一维array类似,二者与Python基本的数据结构List也很相近;
  • Time-Series:以时间为索引的Series;
  • DataFrame:二维的表格型数据结构,可以理解成DataFrame理解为Series的容器;
  • Panel:三维的数组,可以理解为DataFrame的容器;
  • Panel4D:4维数据容器;
  • PanelND:拥有factory集合,可以创建Panel4D一样N维命名容器的模块;

1 Series

import pandas as pd
import numpy as np

首先构建一个Series,如下,会自动添加索引,从0开始

s1 = pd.Series([4, 7, -5, 3])
print(s1)
0    4
1    7
2   -5
3    3
dtype: int64

查看Series的值

s1.values
array([ 4,  7, -5,  3], dtype=int64)

查看Series的索引

s1.index
RangeIndex(start=0, stop=4, step=1)

可以给Series指定索引

s2 = pd.Series([4.0, 6.5, -0.5, 4.2], index = ['d', 'b', 'a', 'c'])
print(s2)
d    4.0
b    6.5
a   -0.5
c    4.2
dtype: float64

通过索引取值

s2["a"]
-0.5

用 in 判断索引是否在Series中

'b' in s2
True

有序字典构建Series

# Series可以看成一个定长的有序字典
dic1 = {'apple':5, 'pen':3, 'applepen':10}
s3 = pd.Series(dic1)
print(s3)
apple        5
pen          3
applepen    10
dtype: int64

2 DataFrame

首先创建一个DataFrame,通过字典构建,也会自动添加索引,从0开始

# DataFrame
data = {'year':[2014,2015,2016,2017],
        'income':[10000,30000,50000,80000],
        'play':[5000,20000,30000,30000]}
df1 = pd.DataFrame(data)
df1
yearincomeplay
02014100005000
120153000020000
220165000030000
320178000030000

指定行和列来构建DataFrame,自动构建表头和索引

df2 = pd.DataFrame(np.arange(12).reshape((3,4)))
df2
0123
00123
14567
2891011

指定行和列来构建DataFrame,指定表头 culumn 和索引 index

df3 = pd.DataFrame(np.arange(12).reshape((3,4)), index=['a','c','b'], columns=[2,33,44,5])
df3
233445
a0123
c4567
b891011

调用列column

df1.columns # 列
Index(['year', 'income', 'play'], dtype='object')

调用行index

df1.index #行
RangeIndex(start=0, stop=4, step=1)

查看值values

df1.values
array([[ 2014, 10000,  5000],
       [ 2015, 30000, 20000],
       [ 2016, 50000, 30000],
       [ 2017, 80000, 30000]], dtype=int64)

可以调用 .describe 描述表,可以得出平均值,标准差等一些表的属性

df1.describe()
yearincomeplay
count4.0000004.0000004.000000
mean2015.50000042500.00000021250.000000
std1.29099429860.78811211814.539066
min2014.00000010000.0000005000.000000
25%2014.75000025000.00000016250.000000
50%2015.50000040000.00000025000.000000
75%2016.25000057500.00000030000.000000
max2017.00000080000.00000030000.000000

使用 .T 转置,行变成列,列变成行

df1.T
0123
year2014201520162017
income10000300005000080000
play5000200003000030000
df3
233445
a0123
c4567
b891011

列排序

df3.sort_index(axis=1) # 列排序
253344
a0312
c4756
b811910

行排序

df3.sort_index(axis=0) # 行排序
233445
a0123
b891011
c4567

指定列排序

df3.sort_values(by=44)
233445
a0123
c4567
b891011
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZPILOTE

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值