使用 pandas 数据框按索引进行移位
make a shift by index with a pandas dataframe
有没有 pandas 的方法:
predicted_sells = []
for row in df.values:
index_tms = row[0]
delta = index_tms + timedelta(hours=1)
try:
sells_to_predict = df.loc[delta]['cars_sold']
except KeyError:
new_element = None
predicted_sells.append(sells_to_predict)
df['sell_to_predict'] = predicted_sells
示例说明:
sell 是我当时 tms 卖出的汽车数量。 sell_to_predict 是我在一小时后售出的汽车数量。我想预测一下。所以我想建立一个新列,其中包含在 tms 时刻我将在 tms+1h
时刻销售的汽车数量
在我的代码之前它看起来像那样
tms sell
2015-11-23 15:00:00 6
2015-11-23 16:00:00 2
2015-11-23 17:00:00 10
看起来像那样
tms sell sell_to_predict
2015-11-23 15:00:00 6 2
2015-11-23 16:00:00 2 10
2015-11-23 17:00:00 10 NaN
我根据另一列的偏移创建了一个新列,但这不是列数的偏移。这是基于索引的移位(这里的索引是时间戳)
这是另一个稍微复杂一点的例子:
之前:
sell random
store hour
1 1 1 9
2 7 7
2 1 4 3
2 2 3
之后:
sell random predict
store hour
1 1 1 9 7
2 7 7 NaN
2 1 4 3 2
2 2 3 NaN
你试过了吗shift
?
例如
df = pd.DataFrame(list(range(4)))
df.columns = ['sold']
df['predict'] = df.sold.shift(-1)
df
sold predict
0 0 1
1 1 2
2 2 3
3 3 NaN
答案是重新采样所以我不会有任何漏洞,然后应用这个问题的答案:How do you shift Pandas DataFrame with a multiindex?
有没有 pandas 的方法:
predicted_sells = []
for row in df.values:
index_tms = row[0]
delta = index_tms + timedelta(hours=1)
try:
sells_to_predict = df.loc[delta]['cars_sold']
except KeyError:
new_element = None
predicted_sells.append(sells_to_predict)
df['sell_to_predict'] = predicted_sells
示例说明:
sell 是我当时 tms 卖出的汽车数量。 sell_to_predict 是我在一小时后售出的汽车数量。我想预测一下。所以我想建立一个新列,其中包含在 tms 时刻我将在 tms+1h
时刻销售的汽车数量在我的代码之前它看起来像那样
tms sell
2015-11-23 15:00:00 6
2015-11-23 16:00:00 2
2015-11-23 17:00:00 10
看起来像那样
tms sell sell_to_predict
2015-11-23 15:00:00 6 2
2015-11-23 16:00:00 2 10
2015-11-23 17:00:00 10 NaN
我根据另一列的偏移创建了一个新列,但这不是列数的偏移。这是基于索引的移位(这里的索引是时间戳)
这是另一个稍微复杂一点的例子:
之前:
sell random
store hour
1 1 1 9
2 7 7
2 1 4 3
2 2 3
之后:
sell random predict
store hour
1 1 1 9 7
2 7 7 NaN
2 1 4 3 2
2 2 3 NaN
你试过了吗shift
?
例如
df = pd.DataFrame(list(range(4)))
df.columns = ['sold']
df['predict'] = df.sold.shift(-1)
df
sold predict
0 0 1
1 1 2
2 2 3
3 3 NaN
答案是重新采样所以我不会有任何漏洞,然后应用这个问题的答案:How do you shift Pandas DataFrame with a multiindex?