【问题标题】:New colum in pandas, based on another column's last valuepandas 中的新列,基于另一列的最后一个值
【发布时间】:2023-03-25 10:40:01
【问题描述】:

在数据框中我得到了这个数据

                     Open        High         Low       Close   Volume  \
-------------------------------------------------------------------------
Date                                                                  
2015-05-01  538.429993  539.539978  532.099976  537.900024  1768200   
2015-05-04  538.530029  544.070007  535.059998  540.780029  1308000   
2015-05-05  538.210022  539.739990  530.390991  530.799988  1383100   
2015-05-06  531.239990  532.380005  521.085022  524.219971  1567000

我的问题是:如果上次收盘价低于当前收盘价,我如何添加一个新列并为其赋值 0,如果高于当前收盘价,则为 1。

如何通过数据框完成这项工作?

【问题讨论】:

  • 如果值相同,应该分配什么值?

标签: python-3.x pandas dataframe


【解决方案1】:
df['increasing'] = (df['Open'].diff() > 0).astype(int)

df['increasing'] = (df['Open'] - df['Open'].shift() > 0).astype(int)

两者都有效,但前者更快。


举个例子,

In [41]: import pandas_datareader.data as pdata

In [42]: df = pdata.get_data_yahoo('AAPL', start='2009-01-02', end='2009-12-31')

In [43]: df.head()
Out[43]: 
                 Open       High        Low      Close     Volume  Adj Close
Date                                                                        
2009-01-02  85.880003  91.040001  85.160000  90.750001  186503800  11.933430
2009-01-05  93.170003  96.179998  92.709999  94.580002  295402100  12.437067
2009-01-06  95.950000  97.170001  92.389998  93.020000  322327600  12.231930
2009-01-07  91.809999  92.500001  90.260003  91.010000  188262200  11.967619
2009-01-08  90.430000  93.150002  90.039998  92.699999  168375200  12.189851

diff() 返回相邻行之间的差异:

In [45]: df['Open'].diff().head()
Out[45]: 
Date
2009-01-02         NaN
2009-01-05    7.290000
2009-01-06    2.779997
2009-01-07   -4.140001
2009-01-08   -1.379999
Name: Open, dtype: float64

(df['Open'].diff() > 0) 返回一个布尔值系列,当差值为正时为 True:

In [46]: (df['Open'].diff() > 0).head()
Out[46]: 
Date
2009-01-02    False
2009-01-05     True
2009-01-06     True
2009-01-07    False
2009-01-08    False
Name: Open, dtype: bool

调用 .astype(int) 会将 False 转换为 0,将 True 转换为 1:

In [47]: (df['Open'].diff() > 0).astype('int').head()
Out[47]: 
Date
2009-01-02    0
2009-01-05    1
2009-01-06    1
2009-01-07    0
2009-01-08    0
Name: Open, dtype: int64

如果你需要赋值,代码会变得有点复杂 第三个可能的值,2,当差值为 0 时:

import numpy as np
diff = df['Open'].diff()
conditions = [diff > 0, diff < 0]
choices = [1, 0]
df['increasing'] = np.select(conditions, choices, default=2)

np.selectnp.where 的泛化。 np.where 适合处理 1 个条件,np.select 处理多个条件。上面的条件是diff &gt; 0diff &lt; 0,我们希望分别赋值1和0:

conditions = [diff > 0, diff < 0]
choices = [1, 0]

当两个条件都不为真时,np.select 分配默认值 2:

df['increasing'] = np.select(conditions, choices, default=2)

【讨论】:

  • 我有点困惑,你能解释一下第一个是做什么的吗?谢谢
  • 非常感谢,这很有意义。再次感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-10
  • 2023-02-07
  • 1970-01-01
  • 2023-03-11
  • 2021-07-17
  • 2022-11-30
相关资源
最近更新 更多