Python量化交易基础——Pandas 学习

阿里云2000元红包!本站用户参与享受九折优惠!


image

dataframe行、列条件运算

1.1 取值操作

from pandas import Series, DataFrame
df = DataFrame({'名称':['东方财富','同花顺','金证股份','东信和平'],
                '编号':['300559','300033','600446','002017'],
                '交易日期':[20180101,20180101,20180101,20180101]})
print(df)
# 根据index和columns取值
s = df.loc[0,'交易日期']
print(s)
     名称      编号      交易日期
0  东方财富  300559  20180101
1   同花顺  300033  20180101
2  金证股份  600446  20180101
3  东信和平  002017  20180101
20180101

1.2 获取第一行和最后一行

df = pd.DataFrame({'a':range(1,5), 'b':['a','b','c','d']})
print(df)
   a  b 
0  1  a 
1  2  b 
2  3  c 
3  4  d
df2 = df.iloc[[0, -1]]
print(df2)
num = result['收盘价'].iloc[-1]  #最后一列单个元素
num = result['收盘价'].iloc[[-1]]  #最后一列一行元素
   a  b
0  1  a
3  4  d

1.3综合小操作(列值递增与基本运算以及文件导入导出)

import pandas as pd
from datetime import date,timedelta
# 完成交易日期递增
def add_month(d,md):
    yd = md // 12
    m  = d.month + md % 12
    if m != 12:
        yd += m // 12
        m = m % 12
    return  date(d.year + yd,m,d.day)
books = pd.read_excel(r'C:\Users\Lenovo\Desktop\excel\Books_data.xlsx',skiprows=3,usecols='C:G',index_col=None
                      ,dtype={'ID':str,'InStore':str,'Date':str})
start = date(2019,1,1)
for i in  books.index:
    books['ID'].at[i] = i + 1
    books['InStore'].at[i] = 'Yes'if i % 2 == 0 else 'N0'
    books['Date'].at[i] = start
    # books['Date'].at[i] = start + timedelta(days=i)
    # books['Date'].at[i] = date(start.year + i,start.month,start.day)
    books['Date'].at[i] = add_month(start,i)
# print(books)
books.set_index('ID',inplace=True)
# books.to_excel(r'C:\Users\Lenovo\Desktop\excel\Books.xlsx')
print('done')
# 列运算
# 具体某列值运算
for i in range(2,6):
    books['Price'].at[i] = books['Price'].at[i] + 2
# # books['Price']= books['Price'] .apply(函数名)  # 自定义一个函数方式
# books['Price']= books['Price'] .apply(lambda x:x+2)
print(books)
       Name InStore        Date  Price
ID                                     
1   Book_001     Yes  2019-01-01     10
2   Book_002      N0  2019-02-01     12
3   Book_003     Yes  2019-03-01     12
4   Book_004      N0  2019-04-01     12
5   Book_005     Yes  2019-05-01     12
6   Book_006      N0  2019-06-01     10
7   Book_007     Yes  2019-07-01     10
8   Book_008      N0  2019-08-01     10
9   Book_009     Yes  2019-09-01     10
10  Book_010      N0  2019-10-01     10

未完,待续……

https://www.jianshu.com/p/b3ab4e2c8105

Python量化投资网携手4326手游为资深游戏玩家推荐:《《龙族幻想》:「巅峰派对」超强福利来临,钻石、礼包、座驾免费领取!

「点点赞赏,手留余香」

    还没有人赞赏,快来当第一个赞赏的人吧!
0 条回复 A 作者 M 管理员
    所有的伟大,都源于一个勇敢的开始!
欢迎您,新朋友,感谢参与互动!欢迎您 {{author}},您在本站有{{commentsCount}}条评论