【问题标题】:DataFrame not saving correct valueDataFrame没有保存正确的值
【发布时间】:2016-04-22 22:39:40
【问题描述】:

我正在处理一个大型数据集,我需要查看同一列中的下一行值是否大于当前值。然后保存 1 或 -1。因此,如果 col d 中的当前行为 1,并且同一 col 中的下一个值为 2,则它将 1 保存在同一行和同一数据帧中的新列 ('e) 上。问题是它总是保存一个值。

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

【问题讨论】:

    标签: python dataframe machine-learning


    【解决方案1】:

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

    np.random.seed(14)  # so you can reproduce
    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
    

    【讨论】:

    • 我使用这个逻辑的方式略有不同,但效果很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-13
    • 1970-01-01
    • 2022-11-19
    • 2012-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多