开源的数据挖掘库,用于数据探索,封装了matplotlib,numpy
import pandas as pd
import numpy as np
# 用numpy正态分布生成数据1000行8列
stock_change=np.random.normal(3,0.6,(1000,8))
stock_change
# 转化为DataFrame格式
stock_code=["股票{}".format(i+1) for i in range(stock_change.shape[0])] #生成行标签
stock_date=pd.date_range(start="20000229",periods=stock_change.shape[1],freq="B") #生成行标签
stock_rise=pd.DataFrame(stock_change,index=stock_code,columns=stock_date)
stock_rise.head(5)
stock_date=pd.date_range(start="20000229",periods=stock_change.shape[1],freq="B") #生成行标签
代码 | 意义 |
---|---|
.shape() | 形状 |
.index() | 列索引值 |
.columns() | 行索引值 |
.values() | 数据值 |
.T | 转置 |
.head() | 展示前五行数据 |
.tail() | 展示后五行数据 |
stock_rise.shape
stock_rise.index
stock_rise.columns
stock_rise.values
stock_rise.T
stock_rise.head()
stock_rise.tail()
1.修改行列索引
必须整行或者整列去进行修改
# 修改行索引
stock_rise.index=["股票——{}".format(i+1) for i in range(stock_rise.shape[0])]
stock_rise.head()
2.重设索引
对象.reset_index()
# 重设索引
stock_rise.reset_index(drop=True) #True是删除原有标签
stock_rise.reset_index(drop=False) #Flase是不删除原有标签生成新标签
3.设置新索引
对象.set_index()
# 设置列为新索引
stock_rise.set_index(['20000229','20000306'])
1.索引操作
import pandas as pd
stock=pd.read_csv("D:\\my_dateset\\National_Stock_Exchange_of_India_Ltd.csv",index_col="Symbol") #index_col="Symbol"设置Symbol为行索引
stock.tail()
# 直接使用行列索引(先列后行)
stock["Low"]["UPL"]
# loc、iloc 先行后列
stock.loc["TECHM":"WIPRO","Chng"]
stock.iloc[:10,3:8] #前10行第4到8列
2.赋值操作
stock["Open"]=100
stock.LTP=100
3.排序
注意by这个参数可以接受多个值,优先按照第一个索引排序,如果相同,按照后面的
stock.sort_values(by=["LTP"],ascending=False)
stock.sort_index()
1.算术运算
stock.query("Chng>5 & Chng<100")
stock[stock["Chng"].isin([-6.25,-6.80])]
3.统计函数