熊猫:计算两行之间的百分比,并将该值添加为一列

时间:2018-12-14 15:58:27

标签: python pandas dataframe

我有一个像这样的数据集:

"Date","Time","Open","High","Low","Close","Volume"

此时间序列表示通用股票市场的价值。

我想计算“关闭”列两行之间的百分比差异(实际上,我想知道股票的价值增加或减少了多少;每一行代表一天)。

我使用for循环完成了此操作(在大数据问题中使用熊猫很糟糕),并且在不同的DataFrame中创建了正确的结果:

rows_number = df_stock.shape[0]

# The first row will be 1, because is calculated in percentage. If haven't any yesterday the value must be 1
percentage_df = percentage_df.append({'Date': df_stock.iloc[0]['Date'], 'Percentage': 1}, ignore_index=True)

# Foreach days, calculate the market trend in percentage
for index in range(1, rows_number):

    # n_yesterday : 100 = (n_today - n_yesterday) : x
    n_today = df_stock.iloc[index]['Close']
    n_yesterday = self.df_stock.iloc[index-1]['Close']
    difference = n_today - n_yesterday
    percentage = (100 * difference ) / n_yesterday

    percentage_df = percentage_df .append({'Date': df_stock.iloc[index]['Date'], 'Percentage': percentage}, ignore_index=True)

我该如何利用dataFrame api重构它,从而删除for循环并在适当的位置创建一个新列?

3 个答案:

答案 0 :(得分:0)

使用diff

(-df['Close'].diff())/df['Close'].shift()

答案 1 :(得分:0)

我建议您首先将Date列用作DateTime索引,以供使用

df_stock = df_stock.set_index(['Date'])
df_stock.index = pd.to_datetime(df_stock.index, dayfirst=True)

然后只需使用日期时间索引访问具有特定列的任何行,并执行任何所需的操作即可,例如,计算“关闭”列的两行之间的百分比差异

df_stock['percentage'] = ((df_stock['15-07-2019']['Close'] - df_stock['14-07-2019']['Close'])/df_stock['14-07-2019']['Close']) * 100

您还可以使用for循环对每个日期或行进行操作:

for Dt in df_stock.index:

答案 2 :(得分:0)

df['Change'] = df['Close'].pct_change()

或者如果您想按相反顺序计算变化:

df['Change'] = df['Close'].pct_change(-1)