有没有一种有效的方法来创建输出以下内容的数组或数据帧(不需要在最左边和最上面的行中使用Price列):
18.00 18.50 17.25 12.50 14.50
Price Date 12/18/1992 12/21/1992 12/22/1992 12/23/1992 12/24/1992
18.00 12/18/1992 0% 3% -4% -31% -19%
18.50 12/21/1992 0% -7% -32% -22%
17.25 12/22/1992 0% -28% -16%
输入将是一个具有1列的csv文件,通过日期列表进行索引。因此,对于上面的示例,它将是:
Date Price
12/18/1992 18.00
12/21/1992 18.50
12/22/1992 17.25
我正在尝试计算每个按时间顺序的日期对的价格变化。所以date_1 / date_0、date_2 / date_0等等。我想在日期对中保留不按时间顺序排列的空格。
到目前为止,我只有……:
import pandas as pd
import numpy as np
import datetime
import matplotlib.pyplot as plt
file_loc = "C:\\Users\\Price Data\\CL1.csv"
df = pd.read_csv(file_loc, parse_dates = True)
df.set_index('Date', inplace = True)
发布于 2018-07-29 03:32:32
看起来您想要创建一个新的数据帧,其中包含第一帧中所有数据的成对比较。您还希望这个新框架具有按价格和日期标记的列和索引。您可以通过在您提供的代码后添加以下代码来实现此目的:
# Get the data for your columns and indices
prices = df['Price']
dates = df.index
# create column/index data as a list
table_labels = list(zip(prices,dates))
# create a dataframe
pairwise_df = pd.DataFrame(columns=table_labels,index=table_labels)
# fill it with your data
# a percentage in the upper triangle, or an empty space in the lower triangle
for p1,d1 in table_labels:
for p2,d2 in table_labels:
pairwise_df.loc[(p1,d1),(p2,d2)] = (p2-p1)/p1*100 if d2 >= d1 else ''
print(pairwise_df)
这应该可以实现我列出的两个目标。
发布于 2018-07-29 11:52:16
你可以像这样使用pandas和numpy函数:
df_out = (pd.crosstab([df['Price'],df['Date']],[df['Price'],df['Date']])
.apply(lambda x: (x.name[0]-x.index.get_level_values(0))/
x.index.get_level_values(0)*100).round(0).astype(int)
.sort_index(level=1)
.sort_index(level=1, axis=1))
df_out = df_out.where(np.triu(np.ones(df_out.shape, dtype=bool)))
df_out
输出:
Price 18.00 18.50 17.25 12.50 14.50
Date 12/18/1992 12/21/1992 12/22/1992 12/23/1992 12/24/1992
Price Date
18.00 12/18/1992 0.0 3.0 -4.0 -31.0 -19
18.50 12/21/1992 NaN 0.0 -7.0 -32.0 -22
17.25 12/22/1992 NaN NaN 0.0 -28.0 -16
12.50 12/23/1992 NaN NaN NaN 0.0 16
14.50 12/24/1992 NaN NaN NaN NaN 0
https://stackoverflow.com/questions/51574119
复制相似问题