pandas高级应用

#分类数据
import pandas as pd
import numpy as np
values = pd.Series(['apple','orange','apple','apple']*2)
values
0     apple
1    orange
2     apple
3     apple
4     apple
5    orange
6     apple
7     apple
dtype: object
pd.unique(values)
array(['apple', 'orange'], dtype=object)
pd.value_counts(values)
apple     6
orange    2
dtype: int64
values = pd.Series([0,1,0,0]*2)
dim = pd.Series(['apple','orange'])
values
0    0
1    1
2    0
3    0
4    0
5    1
6    0
7    0
dtype: int64
dim
0     apple
1    orange
dtype: object
dim.take(values)
0     apple
1    orange
0     apple
0     apple
0     apple
1    orange
0     apple
0     apple
dtype: object
fruits = ['apple', 'orange', 'apple', 'apple'] * 2
N = len(fruits)
df = pd.DataFrame({'fruits':fruits,
                  'basket_id':np.arange(N),
                  'count':np.random.randint(3,15,size=N),
                  'weight':np.random.uniform(0,4,size=N)},
                  columns=['basket_id','fruits','count','weight'])
df
basket_idfruitscountweight
00apple102.679414
11orange82.278047
22apple90.087745
33apple62.028924
44apple111.704697
55orange61.352336
66apple112.940028
77apple42.798046
fruit_cat = df['fruits'].astype('category')
fruit_cat
0     apple
1    orange
2     apple
3     apple
4     apple
5    orange
6     apple
7     apple
Name: fruits, dtype: category
Categories (2, object): [apple, orange]
c = fruit_cat.values #分类对象
type(c)
pandas.core.arrays.categorical.Categorical
c.categories
Index(['apple', 'orange'], dtype='object')
c.codes
array([0, 1, 0, 0, 0, 1, 0, 0], dtype=int8)
df['fruits'] = df['fruits'].astype('category')
df.fruits
0     apple
1    orange
2     apple
3     apple
4     apple
5    orange
6     apple
7     apple
Name: fruits, dtype: category
Categories (2, object): [apple, orange]
my_categories = pd.Categorical(['foo','bar','baz','foo','bar'])
my_categories
[foo, bar, baz, foo, bar]
Categories (3, object): [bar, baz, foo]
categories = ['foo','bar','baz']
codes = [0,1,2,0,0,1]
my_cats_2 = pd.Categorical.from_codes(codes,categories)
my_cats_2
[foo, bar, baz, foo, foo, bar]
Categories (3, object): [foo, bar, baz]
#用分类进行计算
draws = np.random.randn(1000)
draws[:5]
array([ 1.41984629,  0.25818437, -0.78979829,  0.69114415,  0.58610681])
bins = pd.qcut(draws,4)
bins
[(0.714, 3.115], (0.0138, 0.714], (-2.7239999999999998, -0.658], (0.0138, 0.714], (0.0138, 0.714], ..., (-2.7239999999999998, -0.658], (0.714, 3.115], (0.0138, 0.714], (0.0138, 0.714], (0.0138, 0.714]]
Length: 1000
Categories (4, interval[float64]): [(-2.7239999999999998, -0.658] < (-0.658, 0.0138] < (0.0138, 0.714] < (0.714, 3.115]]
bins = pd.qcut(draws,4,labels=['Q1','Q2','Q3','Q4'])
bins
[Q4, Q3, Q1, Q3, Q3, ..., Q1, Q4, Q3, Q3, Q3]
Length: 1000
Categories (4, object): [Q1 < Q2 < Q3 < Q4]
bins = pd.Series(bins,name='quartile')
results = (pd.Series(draws).groupby(bins).agg(['count','min','max']).reset_index())
results
quartilecountminmax
0Q1250-2.722817-0.669126
1Q2250-0.6541610.011138
2Q32500.0163890.713528
3Q42500.7142173.115205
#用分类提高性能
N = 100000
draws = pd.Series(np.random.randn(N))
labels = pd.Series(['foo','bar','baz','qux']*(N//4))
categories = labels.astype('category')
labels.memory_usage()#占用内存
800080
categories.memory_usage()
100272
#分类方法
s = pd.Series(['a','b','c','d']*2)
cat_s = s.astype('category')
cat_s
0    a
1    b
2    c
3    d
4    a
5    b
6    c
7    d
dtype: category
Categories (4, object): [a, b, c, d]
cat_s.cat.codes
0    0
1    1
2    2
3    3
4    0
5    1
6    2
7    3
dtype: int8
cat_s.cat.categories
Index(['a', 'b', 'c', 'd'], dtype='object')
actual_categories = ['a','b','c','d','e']
cat_s2 = cat_s.cat.set_categories(actual_categories)
cat_s2
0    a
1    b
2    c
3    d
4    a
5    b
6    c
7    d
dtype: category
Categories (5, object): [a, b, c, d, e]
cat_s2.value_counts()
d    2
c    2
b    2
a    2
e    0
dtype: int64
#为建模创建虚拟变量
cat_s = pd.Series(['a','b','c','d']*2,dtype='category')
pd.get_dummies(cat_s)
abcd
01000
10100
20010
30001
41000
50100
60010
70001
#GroupBy高级应用
#分组转换和解封
df = pd.DataFrame({'key':['a','b','c']*4,
                  'value':np.arange(12.)})
df
keyvalue
0a0.0
1b1.0
2c2.0
3a3.0
4b4.0
5c5.0
6a6.0
7b7.0
8c8.0
9a9.0
10b10.0
11c11.0
g = df.groupby('key').value
g.mean()
key
a    4.5
b    5.5
c    6.5
Name: value, dtype: float64
g.transform(lambda x:x.mean())
0     4.5
1     5.5
2     6.5
3     4.5
4     5.5
5     6.5
6     4.5
7     5.5
8     6.5
9     4.5
10    5.5
11    6.5
Name: value, dtype: float64
g.transform('mean')
0     4.5
1     5.5
2     6.5
3     4.5
4     5.5
5     6.5
6     4.5
7     5.5
8     6.5
9     4.5
10    5.5
11    6.5
Name: value, dtype: float64
g.transform(lambda x:x*2)
0      0.0
1      2.0
2      4.0
3      6.0
4      8.0
5     10.0
6     12.0
7     14.0
8     16.0
9     18.0
10    20.0
11    22.0
Name: value, dtype: float64
g.transform(lambda x:x.rank(ascending=False))
0     4.0
1     4.0
2     4.0
3     3.0
4     3.0
5     3.0
6     2.0
7     2.0
8     2.0
9     1.0
10    1.0
11    1.0
Name: value, dtype: float64
#分组的时间重采样
N = 15
times = pd.date_range('2017-05-20 00:00',freq='1min',periods=N)
df = pd.DataFrame({'time':times,
                  'values':np.arange(N)})
df
timevalues
02017-05-20 00:00:000
12017-05-20 00:01:001
22017-05-20 00:02:002
32017-05-20 00:03:003
42017-05-20 00:04:004
52017-05-20 00:05:005
62017-05-20 00:06:006
72017-05-20 00:07:007
82017-05-20 00:08:008
92017-05-20 00:09:009
102017-05-20 00:10:0010
112017-05-20 00:11:0011
122017-05-20 00:12:0012
132017-05-20 00:13:0013
142017-05-20 00:14:0014
df.set_index('time').resample('5min').count()
values
time
2017-05-20 00:00:005
2017-05-20 00:05:005
2017-05-20 00:10:005
df2 = pd.DataFrame({'time': times.repeat(3),
                     'key': np.tile(['a', 'b', 'c'], N),
                        'value': np.arange(N * 3.)})
df2


timekeyvalue
02017-05-20 00:00:00a0.0
12017-05-20 00:00:00b1.0
22017-05-20 00:00:00c2.0
32017-05-20 00:01:00a3.0
42017-05-20 00:01:00b4.0
52017-05-20 00:01:00c5.0
62017-05-20 00:02:00a6.0
72017-05-20 00:02:00b7.0
82017-05-20 00:02:00c8.0
92017-05-20 00:03:00a9.0
102017-05-20 00:03:00b10.0
112017-05-20 00:03:00c11.0
122017-05-20 00:04:00a12.0
132017-05-20 00:04:00b13.0
142017-05-20 00:04:00c14.0
152017-05-20 00:05:00a15.0
162017-05-20 00:05:00b16.0
172017-05-20 00:05:00c17.0
182017-05-20 00:06:00a18.0
192017-05-20 00:06:00b19.0
202017-05-20 00:06:00c20.0
212017-05-20 00:07:00a21.0
222017-05-20 00:07:00b22.0
232017-05-20 00:07:00c23.0
242017-05-20 00:08:00a24.0
252017-05-20 00:08:00b25.0
262017-05-20 00:08:00c26.0
272017-05-20 00:09:00a27.0
282017-05-20 00:09:00b28.0
292017-05-20 00:09:00c29.0
302017-05-20 00:10:00a30.0
312017-05-20 00:10:00b31.0
322017-05-20 00:10:00c32.0
332017-05-20 00:11:00a33.0
342017-05-20 00:11:00b34.0
352017-05-20 00:11:00c35.0
362017-05-20 00:12:00a36.0
372017-05-20 00:12:00b37.0
382017-05-20 00:12:00c38.0
392017-05-20 00:13:00a39.0
402017-05-20 00:13:00b40.0
412017-05-20 00:13:00c41.0
422017-05-20 00:14:00a42.0
432017-05-20 00:14:00b43.0
442017-05-20 00:14:00c44.0
time_key = pd.TimeGrouper('5min')
resampled = (df2.set_index('time').groupby(['key',time_key]).sum())
resampled
C:\Anaconda\lib\site-packages\ipykernel_launcher.py:1: FutureWarning: pd.TimeGrouper is deprecated and will be removed; Please use pd.Grouper(freq=...)
  """Entry point for launching an IPython kernel.
value
keytime
a2017-05-20 00:00:0030.0
2017-05-20 00:05:00105.0
2017-05-20 00:10:00180.0
b2017-05-20 00:00:0035.0
2017-05-20 00:05:00110.0
2017-05-20 00:10:00185.0
c2017-05-20 00:00:0040.0
2017-05-20 00:05:00115.0
2017-05-20 00:10:00190.0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值