python - 在 Pandas 中执行此操作的更好方法?
问题描述
我只是在寻求一些关于如何更好地做到这一点的指导。我只是在做一些基础研究来比较周一的开盘价和低点。代码代码返回两个列表,一个带有回报(周一收盘 - 开盘/周一开盘)和一个只有 1 和 0 的列表,以反映回报是正数还是负数。
请看一下,因为我确信在熊猫中有更好的方法,但我只是不知道如何。
#Monday only
m_list = [] #results list
h_list = [] #hit list (close-low > 0)
n=0 #counter variable
for t in history.index:
if datetime.datetime.weekday(t[1]) == 1: #t[1] is the timestamp in multi index (if timestemp is a Monday)
x = history.ix[n]['open']-history.ix[n]['low']
m_list.append((history.ix[n]['open']-history.ix[n]['low'])/history.ix[n]['open'])
if x > 0:
h_list.append(1)
else:
h_list.append(0)
n += 1 #add to index counter
else:
n += 1 #add to index counter
print("Mean: ", mean(m_list), "Max: ", max(m_list),"Min: ",
min(m_list), "Hit Rate: ", sum(h_list)/len(h_list))
解决方案
您可以直接这样做:
(history['open']-history['low'])>0
这将为您true
提供更大的行open
和更大flase
的行low
。
如果需要1,0
,可以将上述语句乘以 1。
((history['open']-history['low'])>0)*1
例子
import numpy as np
import pandas as pd
df = pd.DataFrame({'a':np.random.random(10),
'b':np.random.random(10)})
打印数据框:
print(df)
a b
0 0.675916 0.796333
1 0.044582 0.352145
2 0.053654 0.784185
3 0.189674 0.036730
4 0.329166 0.021920
5 0.163660 0.331089
6 0.042633 0.517015
7 0.544534 0.770192
8 0.542793 0.379054
9 0.712132 0.712552
要创建一个新列compare
,其中 1 if a
is greater 和 9 if b
is greater :
df['compare'] = (df['a']-df['b']>0)*1
这将添加新列compare
:
a b compare
0 0.675916 0.796333 0
1 0.044582 0.352145 0
2 0.053654 0.784185 0
3 0.189674 0.036730 1
4 0.329166 0.021920 1
5 0.163660 0.331089 0
6 0.042633 0.517015 0
7 0.544534 0.770192 0
8 0.542793 0.379054 1
9 0.712132 0.712552 0
推荐阅读
- c++ - C++ Qt QPixmap 加载总是返回 false
- angular - 如何更改Angular Material中数据表标题中排序箭头的颜色?
- node.js - 尝试从 git hub node.js 版本 v6.10.0 安装 MERN-Social-Network
- java - 从现有的 jhipster 生成的应用程序重构为 Spring Boot 应用程序
- javafx - Netbeans 9 0 Java FX 10
- scala - Spark:列表或列表缓冲区
- ios - 重复本地通知会删除先前待处理的本地通知
- c# - 如何为要在 ASP.net 核心中下载的文件创建可下载文件链接
- swift - Post A Json object as parameter value in Swift 4 ios using Alamofire
- android - 如何指定哪些 sharedPreferences 自动备份?