pandas的基本用法(三)——设置数据

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

本文主要是关于pandas的一些基本用法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#!/usr/bin/env python
# _*_ coding: utf-8 _*_

import pandas as pd
import numpy as np


# Test 1
# 定义数据
dates = pd.date_range('20170101', periods = 6)
print dates

df = pd.DataFrame(np.arange(24).reshape((6, 4)), index = dates, columns = ['A', 'B', 'C', 'D'])
print df

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

A B C D
2017-01-01 0 1 2 3
2017-01-02 4 5 6 7
2017-01-03 8 9 10 11
2017-01-04 12 13 14 15
2017-01-05 16 17 18 19
2017-01-06 20 21 22 23

# Test 2
# 设置df[2,2]为100
df.iloc[2, 2] = 100
print df

# loc设置值
df.loc['20170102', 'C'] = 999
print df

# 根据条件设置值
df[df.A > 8] = 0
print df

# 根据ix设置值
df.ix[[0, 2], ['A', 'C']] = 888
print df

# 限定设置区域
df.B[df.B == 0] = 6
print df

# Test 2 result
A B C D
2017-01-01 0 1 2 3
2017-01-02 4 5 6 7
2017-01-03 8 9 100 11
2017-01-04 12 13 14 15
2017-01-05 16 17 18 19
2017-01-06 20 21 22 23

A B C D
2017-01-01 0 1 2 3
2017-01-02 4 5 999 7
2017-01-03 8 9 100 11
2017-01-04 12 13 14 15
2017-01-05 16 17 18 19
2017-01-06 20 21 22 23

A B C D
2017-01-01 0 1 2 3
2017-01-02 4 5 999 7
2017-01-03 8 9 100 11
2017-01-04 0 0 0 0
2017-01-05 0 0 0 0
2017-01-06 0 0 0 0

A B C D
2017-01-01 888 1 888 3
2017-01-02 4 5 999 7
2017-01-03 888 9 888 11
2017-01-04 0 0 0 0
2017-01-05 0 0 0 0
2017-01-06 0 0 0 0

A B C D
2017-01-01 888 1 888 3
2017-01-02 4 5 999 7
2017-01-03 888 9 888 11
2017-01-04 0 6 0 0
2017-01-05 0 6 0 0
2017-01-06 0 6 0 0

# Test 3
# 添加一列
df['F'] = None
print df

# 添加一列
df['E'] = pd.Series([1, 2, 3, 4, 5, 6], index = dates)
print df

# Test 3 result
A B C D F
2017-01-01 888 1 888 3 None
2017-01-02 4 5 999 7 None
2017-01-03 888 9 888 11 None
2017-01-04 0 6 0 0 None
2017-01-05 0 6 0 0 None
2017-01-06 0 6 0 0 None

A B C D F E
2017-01-01 888 1 888 3 None 1
2017-01-02 4 5 999 7 None 2
2017-01-03 888 9 888 11 None 3
2017-01-04 0 6 0 0 None 4
2017-01-05 0 6 0 0 None 5
2017-01-06 0 6 0 0 None 6

参考资料

  1. https://www.youtube.com/user/MorvanZhou
如果有收获,可以请我喝杯咖啡!