问题描述
我是 Python 新手,我想根据我在列中的移位单元执行某种移位。 我的数据如下:
团价
1 0.1
1 0.2
1 0.3
2 0.9
2 0.12
第一组的shift_Unit为2,第二组为1
所需的输出如下:
组 Shifted_Rate
1 0
1 0
1 0.1
2 0
2 0.9
我尝试执行以下操作,但不起作用: df['Shifted_Rate'] = df['Rate'].shift(df['Shift_Unit'])
解决方法
我认为这可能是我第一次与 pandas
合作,所以这可能没有帮助,但根据我在 the documentation 中找到的 pandas.DataFrame.shift()
,它看起来与“要移动的周期数”相关的 periods
变量是 int
。正因为如此(也就是说,因为这是一个 int
而不是像 list
或 dict
这样的东西),我觉得您可能需要通过使单独的数据框,然后将这些数据框放在一起。我尝试了这个并使用 pandas.DataFrame.append()
将各个数据框放在一起。使用 pandas
可能有更有效的方法来执行此操作,但就目前而言,我希望这对您当前的情况有所帮助。
这是我用来处理您的情况的代码(在我的情况下,此代码位于名为 q11.py
的文件中):
import numpy as np
import pandas as pd
# The periods used for the shifting of each group
# (e.g.,'1' is for group 1,'2' is for group 2).
# You can add more items here later if need be.
periods = {
'1': 2,'2': 1
}
# Building the first DataFrame
df1 = pd.DataFrame({
'Rate': pd.Series([0.1,0.2,0.3],index=[1,1,1]),})
# Building the second DataFrame
df2 = pd.DataFrame({
'Rate': pd.Series([0.9,0.12],index=[2,2]),})
# Shift
df1['Shifted_Rate'] = df1['Rate'].shift(
periods=periods['1'],fill_value=0
)
df2['Shifted_Rate'] = df2['Rate'].shift(
periods=periods['2'],fill_value=0
)
# Append the df2 DataFrame to df1 and save the result to a new DataFrame df3
# ref: https://pythonexamples.org/pandas-append-dataframe/
# ref: https://stackoverflow.com/a/51953935/1167750
# ref: https://stackoverflow.com/a/40014731/1167750
# ref: https://pandas.pydata.org/pandas-docs/stable/reference/api
# /pandas.DataFrame.append.html
df3 = df1.append(df2,ignore_index=False)
# ref: https://stackoverflow.com/a/18023468/1167750
df3.index.name = 'Group'
print("\n",df3,"\n")
# Optional: If you only want to keep the Shifted_Rate column:
del df3['Rate']
print(df3)
运行程序时,输出应如下所示:
$ python3 q11.py
Rate Shifted_Rate
Group
1 0.10 0.0
1 0.20 0.0
1 0.30 0.1
2 0.90 0.0
2 0.12 0.9
Shifted_Rate
Group
1 0.0
1 0.0
1 0.1
2 0.0
2 0.9