Python Pandas,pythonpandas,引入方式import
Python Pandas,pythonpandas,引入方式import
引入方式
import pandas as pd
准备数据
import numpy as npstock_cnt = 200view_days = 504# 生成序列stock_day_change = np.random.standard_normal((stock_cnt, view_days))stock_day_change.shape
列出前5行数据
pd.DataFrame(stock_day_change).head(5)
4.1.2 索引行列序列
# 从2017-1-1向上时间递进,单位freq=‘1d‘即1天days = pd.date_range(‘2017-1-1‘, periods=stock_day_change.shape[1], freq=‘1d‘)# 股票0 -> 股票stock_day_change.shape[0]stock_symbols = [‘股票 ‘ + str(x) for x in range(stock_day_change.shape[0])]# 分别设置index和columnsdf = pd.DataFrame(stock_day_change, index=stock_symbols, columns=days)df.head(2)
df_stock0 = df[‘股票 0‘]print(type(df_stock0))# 打印出Series的前5行数据, 与DataFrame一致# <class ‘pandas.core.series.Series‘>df_stock0.head()
4.2.1 数据整体分析
#info()查看数据是否有缺失,及各个子数据的数据类型tsla_df.info()#describe()展示每组数据的统计信息tsla_df.describe()
4.2.2 索引选取和切片选择
#使用loc配合行名称、列名称选取切片示例如下# 2014-07-23至2014-07-31 开盘价格序列tsla_df.loc[‘2014-07-23‘:‘2014-07-31‘, ‘open‘]
iloc配合行索引数值及列索引数值选取切片
# [1:5]:(1,2,3,4),[2:6]: (2, 3, 4, 5)tsla_df.iloc[1:5, 2:6]
根据列名混合选择
tsla_df.[[‘close‘,‘high‘,‘low‘]][0:3]
4.2.3 逻辑条件进行数据筛选
# abs为取绝对值# 涨跌幅大于8%,交易成交量大于统计周期内的平均值的2.5倍tsla_df[(np.abs(tsla_df.netChangeRatio) > 8) & (tsla_df.volume > 2.5 * tsla_df.volume.mean())]
4.2.4 数据转换与规整
tsla_df.sort_index(by=‘netChangeRatio‘)[:5]
# 如果一行的数据中存在na就删除这行tsla_df.dropna() # 通过how控制 如果一行的数据中全部都是na就删除这行tsla_df.dropna(how=‘all‘)
# 使用指定值填充na, inplace代表就地操作,即不返回新的序列在原始序列上修改tsla_df.fillna(tsla_df.mean(), inplace=True).head()# pct_change()对序列从第二项开始向前做减法后再除以前一项,即涨跌幅tsla_df.close.pct_change()[:3]
# 将change_ratio转变成与tsla_df.p_change字段一样的百分百,同样保留两位小数np.round(change_ratio[-5:] * 100, 2)
4.2.5 数据本地序列化操作
tsla_df.to_csv(‘../gen/tsla_df.csv‘, columns=tsla_df.columns, index=True)tsla_df_load = pd.read_csv(‘../gen/tsla_df.csv‘, parse_dates=True, index_col=0)tsla_df_load.head()
Python Pandas
相关内容
- Python 二级模拟选择题(八),python模拟选择题,1. 数据
- python3 for循环-range遍历,python3-range,for循环、rang
- python2与python3的区别,python2python3,为什么要有pytho
- python-Zip方法,,zip返回一个将多个
- Python文件,,1.文件读模式 rf
- python之路---04 列表 元组,python---04,十七 、列表
- python-爬取中药信息,python-爬中药,1.选一个自己感兴趣
- 用十张图详解TensorFlow数据读取机制(附代码),十张
- 浅谈python在提示符下使用open打开文件失败的原因及解决
- python如何统计序列中元素,python统计序列
评论关闭