DataFrame 未能正确保存值

我正在处理一个大型数据集,需要检查同一列的下一行值是否大于当前值。如果是,则保存1或-1。例如,如果当前行在列d中的值为1,且同一列的下一值为2,则在同一行和同一DataFrame的新列’e’中保存1。问题是它总是保存单一值。

import numpy as np
import pandas as pd
df1 = pd.DataFrame(np.random.randn(10, 4), columns=['a', 'b', 'c', 'd'])
mask = df1.applymap(lambda x: x <-0.7)
df1 = df1[-mask.any(axis=1)]
sLength = len(df1['a'])
rwno=0
PrevClose=[]
for index,row  in df1.iterrows():
    Close=row.iloc[3]
    PrevClose.append(Close)
    rwno+=1
print df1
rwno=1
for index,row  in df1.iterrows():
    NxtDaySpy=0
    if rwno < len(df1.index) :
        NextClose=PrevClose[rwno]
        Close=row.iloc[3]
        df1['e']=pd.Series((NextClose-Close)/abs(NextClose-Close), index=df1.index)
    rwno+=1
print df1.head

回答:

假设你有一个只有一列的数据框,为了简单起见。

np.random.seed(14)  # 这样你可以重现
df = pd.DataFrame(np.random.randn(10, 1), columns=['a'])
df.head()
--------- a
--------- 1.331587
1.331587
0.715279
-1.545400
-0.008384
0.621336

你可以使用 shift() 来延迟(或提前)你的数据。

df['a_new'] = df.shift(periods=1).fillna(0.0)
df.head()
--------------------- a           a_new
--------------------- 1.331587    0.000000
0.715279    1.331587
-1.545400    0.715279
-0.008384   -1.545400
0.621336   -0.008384

然后使用列表解析来获取你的 1-1 值。

df['a_flags'] = [1 if x > y else -1 for x, y in zip(df.a, df.a_new)]
df.head()
------------------------------- a           a_new       a_flag
------------------------------- 1.331587    0.000000    1
0.715279    1.331587   -1
-1.545400    0.715279   -1
-0.008384   -1.545400    1
0.621336   -0.008384    1

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注