为数据科学处理 Pandas 中的 Concat 和 Shift 功能

数据挖掘 Python 神经网络 熊猫 数据框
2022-02-01 23:33:42

我正在尝试使用滞后功能和 Concat() 和 Shift() 功能,

    seies = Series.from_csv('sugar_price_2.csv', header=0, sep=';')

    In [25]: prices = DataFrame(series.values)

    In [26]: dataframe = concat([prices.shift(3), prices.shift(2), prices.shift(1), prices], axis=1)

    In [27]: dataframe.coloumns = ['t-2', 't-1', 't', 't+1']

    In [28]: print(dataframe.head(20))

       0       0       0     0      
0      NaN     NaN     NaN  2800
1      NaN     NaN  2800.0  2800
2      NaN  2800.0  2800.0  2800
3   2800.0  2800.0  2800.0  2800
4   2800.0  2800.0  2800.0  2800
5   2800.0  2800.0  2800.0  2800

但是 't-2', 't-1', 't' 列名没有出现。

谁能说出我的代码有什么问题...

1个回答

正如@Stephan Rauch在他的评论中指出的那样,列的名称存储在dataframe.columns- OP 有一个错字。

下面是一个使用虚拟数据的工作示例,获得与用户相同的输出 - 使用一个小循环来计算移位值。

from pandas import DataFrame

prices = dict(
    col1=[0, 1, 2, 3, 4, 5, 6],
    col2=[2, 3, 4, 5, 6, 7, 8],
    col3=[5, 6, 7, 8, 9, 10, 11],
    col4=[12, 13, 14, 15, 16, 17, 18])

dataframe = DataFrame.from_dict(prices)
print(dataframe)
new_col_names = ['t-2', 't-1', 't', 't+1']
dataframe.columns = new_col_names
print(dataframe)

# Number of columns we have
N = len(dataframe.columns)

for n, col in enumerate(dataframe.columns):
    shift_by = N - n - 1  # don't shift the final column
    dataframe[col] = dataframe[col].shift(periods=shift_by, axis=0)

print(dataframe)

# If desired, remove the new NaNs that appear in the first
final_dataframe = dataframe.drop(labels=dataframe.index[:N - 1], axis='index')
print(final_dataframe)