09 pandas DataFrame - 排序、排名、时间序列

=== 排序 ===

原数据:
data1 = pd.DataFrame(np.random.randint(0,9,[5,5]),
                     index=list('abcde'),
                     columns=list('ABCDE'))
1、索引排序 sort_index

ascending默认True 升序
axis默认0 行索引

data1.sort_index(ascending=False,axis=1)
img_916b40a02087de93da48e502025d725c.png
2、值排序 sort_values
sort_values 默认列排序
data1.sort_values('E')
img_ebfb9b826480f76a5f91daf98182e617.png
sort_values 行排序
data1.T.sort_values(by='a').T
img_5c58a49b32279feb0147013e6c73d8e5.png
下面行排序的写法始终报错,不知为何
data1.sort_values(by='a',axis=1,ascending=False)

ValueError: When sorting by column, axis must be 0 (rows)

3、所有行或列排序
data1.apply(np.sort,axis = 1) 
img_b3386138affb61876e7bc9cb22f92ac8.png
image.png

=== 排名 ===

场景:数据的位置还是原来的位置(不排序),但我想知道是第几名
原数据:
ser1 = pd.Series([3,1,5,2,5],index=list('abcde'))
ser1
a    3
b    1
c    5
d    2
e    5
dtype: int64
排名 rank

参数 method 默认='average' max、min 共用最大最小;first 第一次出现的排名靠前

ser1.rank(method='first')
a    3.0
b    1.0
c    4.0
d    2.0
e    5.0
dtype: float64

=== 时间序列 ===

1、 创建苹果12个月的股票值
apple_share = pd.Series(np.random.randint(1000,3400,12))
apple_share
0     1509
1     2806
2     1030
3     1084
4     3023
5     3098
6     3289
7     3003
8     1544
9     2442
10    1226
11    1767
dtype: int32
2、 生成时间序列

默认以天生成
以月份来生成 freq='M' 天=D
如果不确定结束时间,可以制定生成多少个 periods

apple_index = pd.date_range(start='20170101',periods=12,freq="M")
apple_index = pd.date_range(start='20170101',end='20171231',freq="M")
apple_index
DatetimeIndex(['2017-01-31', '2017-02-28', '2017-03-31', '2017-04-30',
               '2017-05-31', '2017-06-30', '2017-07-31', '2017-08-31',
               '2017-09-30', '2017-10-31', '2017-11-30', '2017-12-31'],
              dtype='datetime64[ns]', freq='M')
3、 创建苹果股票的日期序列
apple_share.index = apple_index
apple_share
2017-01-31    1509
2017-02-28    2806
2017-03-31    1030
2017-04-30    1084
2017-05-31    3023
2017-06-30    3098
2017-07-31    3289
2017-08-31    3003
2017-09-30    1544
2017-10-31    2442
2017-11-30    1226
2017-12-31    1767
Freq: M, dtype: int32
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值