背景
学习了 numpy 用pandas这个利器就非常棒了,前提是要学习好numpy 他是一个基础
基础学习
Series
import pandas as pd
from pandas import Series, DataFrame
x = Series([1,2,3,4])
print(x)
print(x.values)
print(x.index)
x = Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
print(x)
print(x[x > 2]) # 将值大于2 的值给拿出来
x = Series(["yang", "xiao", "dong"], index=['a', 'b', 'c'])
print(x)
print(x.index)
print(x['a'])
print(x[['c', 'a', 'b']]) # 花式索引
print('b' in x) # in 使用指的是 index 中的元素
print('t' in x)
print("使用字典来生成series")
data = {
'a':1, 'b':2, 'c':3}
x = Series(data)
print(x)
# a 1
# b 2
# c 3
# dtype: int64
print("使用字典生成Series 并指定额外的index, 不匹配的索引部分数据为NaN")
data = {
'a':1, 'b':2, 'c':3}
exindex = ['a', 'b', 'c', 'd']
y = Series(data, index=exindex)
print(y)
# a 1.0
# b 2.0
# c 3.0
# d NaN
# dtype: float64
区分
上面这已经有index的情况下 替换的, 没有匹配的话显示为NaN 但是 如果开始就没有index 的话多写或者少些 index 都会有错误
x = Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd', 'e'])
print(x)
File "C:\Python36\lib\site-packages\pandas\core\internals.py", line 120, in __init__
len(self.mgr_locs)))
ValueError: Wrong number of items passed 4, placement implies 5
数据结构DataFrame
DataFrame是一个类似表格的数据结构,索引包括列索引和行索引,包含有一组有序的列,每列可以是不同的值类型(数值、字符串、布尔值等)。DataFrame的每一行和每一列都是一个Series,这个Series的name属性为当前的行索引名/列索引名。
通过列索引获取列数据(Series类型 ):df_obj[col_idx] 或 df_obj.col_idx
.ix,标签与位置混合索引
可输入给DataFrame构造器的数据:
DataFrame的使用代码示例:
print("使用字典生成DataFrame, key 为列名")
data = {
"state": ['ok', 'ok', 'good', 'bad'],
'year':[1992, 1993, 1994, 1995],
'pop': [3.7, 3.4, 3.5, 0.9]
}
print(DataFrame(data))
# 使用字典生成DataFrame, key 为列名
# pop state year
# 0 3.7 ok 1992
# 1 3.4 ok 1993
# 2 3.5 good 1994
# 3 0.9 bad 1995
print("制定索引列,不匹配为NaN")
print(DataFrame(data, columns=['year', 'state', 'pop', 'debt']))
# 制定索引列,不匹配为NaN
# year state pop debt
# 0 1992 ok 3.7 NaN
# 1 1993 ok 3.4 NaN
# 2 1994 good 3.5 NaN
# 3 1995 bad 0.9 NaN
上面是制定列头现在指定索引 每行的索引
x = DataFrame(data, columns=['year', 'state', 'pop', 'debt'], index=['one', 'two', 'three', 'four'])
print(x)
# year state pop debt
# one 1992 ok 3.7 NaN
# two 1993 ok 3.4 NaN
# three 1994 good 3.5 NaN
# four 1995 bad 0.9 NaN
索引修改值
import pandas as pd
from pandas import Series, DataFrame
print("使用字典生成DataFrame, key 为列名")
data = {
"state": ['ok', 'ok', 'good', 'bad'],
'year':[1992, 1993, 1994, 1995],
'pop': [3.7, 3.4, 3.5, 0.9]
}
x = DataFrame(data, columns=['year', 'state', '