目录
pandas核心数据结构
Series
Series 是一维带标签的数组,数组里可以放任意的数据(整数,浮点数,字符串,Python Object)。其基本的创建函数是:
s = pd.Series(data, index=index)
其中 index 是一个列表,用来作为数据的标签;
data 可以是不同的数据类型:
- Python 字典
- ndarray 对象
- 一个标量值,如 5
从ndarray创建
s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e'])
s
运行结果为:
a 0.747292
b -1.120276
c -0.132692
d -0.267813
e -0.590904
从字典创建
# 空值的默认处理
d = {'a' : 0., 'b' : 1., 'd' : 3}
s = pd.Series(d, index=list('abcd'))
s
运行结果为:
a 0
b 1
c NaN
d 3
从标量创建
pd.Series(3, index=list('abcde'))
运行结果为:
a 3
b 3
c 3
d 3
e 3
Series 是类 ndarray 对象
s = pd.Series(np.random.randn(5))
可做如下操作:
s[0]
s[:3]
s[[1, 3, 4]]
np.exp(s)
np.sin(s)
Series 是类字典对象
s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e'])
可做如下操作:
s['a']
s['e'] = 5
s['g'] = 100
'e' in s
print s.get('f')
print s.get('f', np.nan) # 得到的空值返回为NaN
属性:标签对齐
s1 = pd.Series(np.random.randn(3), index=['a', 'c', 'e'])
s2 = pd.Series(np.random.randn(3), index=['a', 'd', 'e'])
print '{0}\n\n{1}'.format(s1, s2)
s1 + s2
运行结果为:
a -0.917905
c -0.744616
e 0.114522
a 0.721087
d -0.471575
e 0.796093
a -0.196818
c NaN
d NaN
e 0.910615
属性:name
s = pd.Series(np.random.randn(5), name='Some Thing')
s.name
运行结果为:
'Some Thing'
DataFrame
DataFrame 是二维带行标签和列标签的数组。可以把 DataFrame 想象成一个 Excel 表格或一个 SQL 数据库的表格,还可以想象成是一个 Series 对象字典。它是 Pandas 里最常用的数据结构。
创建 DataFrame 的基本格式是:
df = pd.DataFrame(data, index=index, columns=columns)
其中 index 是行标签,columns 是列标签,dat