Python pandas获取基于过去一年的滚动数据,并在数据框中创建列
我有一个包含3列的数据框架,包括a、B、C。我需要使用B、C列创建列,如下面的输出部分所示 数据帧:Python pandas获取基于过去一年的滚动数据,并在数据框中创建列,python,pandas,numpy,pivot,pandas-groupby,Python,Pandas,Numpy,Pivot,Pandas Groupby,我有一个包含3列的数据框架,包括a、B、C。我需要使用B、C列创建列,如下面的输出部分所示 数据帧: A B C C_1 pink 1971 C_1 pink 1972 C_1 blue 1972 C_1 red 1973 C_1 pink 1973 C_1 white 1974 输出: 这里是第一排,C年是1971年,这是最
A B C
C_1 pink 1971
C_1 pink 1972
C_1 blue 1972
C_1 red 1973
C_1 pink 1973
C_1 white 1974
输出:
这里是第一排,C年是1971年,这是最小的一年,b列计数是1,因此对于这一行,b_cnt_C-0的输出应该是1,而且应该是0,因为我们在1971年之前没有信息,但是对于第二行和第三行,v有1971年和1972年的信息。因此,对于第二行和第三行,输出应该如下所示,对于所有剩余行,程序相同
A B C B_cnt_C-0 B_cnt_C-1 B_cnt_C-2 B_cnt_C-3
C_1 pink 1971 1 0 0 0
C_1 pink 1972 2 1 0 0
C_1 blue 1972 2 1 0 0
C_1 red 1973 2 2 1 0
C_1 pink 1973 2 2 1 0
C_1 white 1974 1 2 2 1
使用:
包含更多组的解决方案:
print (df)
A B C
0 C_1 pink 1971
1 C_1 pink 1972
2 C_1 blue 1972
3 C_1 red 1973
4 C_1 pink 1973
5 C_1 white 1974
6 C_2 pink 1975
7 C_2 pink 1976
8 C_3 blue 1976
9 C_3 red 1978
10 C_3 pink 1979
11 C_3 white 1979
非常感谢你的回复,我会检查你的解决方案,让你知道它是否有效me@ram-当然,如果没有,让我知道问题是什么。接受它,我还有一个问题,我想发布它,但它说要等待90分钟才能发布。一旦我发布了另一个,我会在这里给你一个问题的url。你能看看吗it@ram-你确定吗?没有绿色的记号。是的,耶茨雷尔,它说记录下来的名声不到15个,我想这可能需要一些时间,我是新来的
print (df)
A B C
0 C_1 pink 1971
1 C_1 pink 1972
2 C_1 blue 1972
3 C_1 red 1973
4 C_1 pink 1973
5 C_1 white 1974
6 C_2 pink 1975
7 C_2 pink 1976
8 C_3 blue 1976
9 C_3 red 1978
10 C_3 pink 1979
11 C_3 white 1979
s = df.groupby(['A','C'])['B'].nunique()
a = df.groupby('A')['C'].nunique().max()
df1 = pd.concat([s.groupby(level=0).shift(x).fillna(0, downcast='int')
for x in range(a)], axis=1)
df1.columns = ['B_cnt_C-{}'.format(x) for x in range(len(df1.columns))]
df = df.join(df1, on=['A','C'])
print (df)
A B C B_cnt_C-0 B_cnt_C-1 B_cnt_C-2 B_cnt_C-3
0 C_1 pink 1971 1 0 0 0
1 C_1 pink 1972 2 1 0 0
2 C_1 blue 1972 2 1 0 0
3 C_1 red 1973 2 2 1 0
4 C_1 pink 1973 2 2 1 0
5 C_1 white 1974 1 2 2 1
6 C_2 pink 1975 1 0 0 0
7 C_2 pink 1976 1 1 0 0
8 C_3 blue 1976 1 0 0 0
9 C_3 red 1978 1 1 0 0
10 C_3 pink 1979 2 1 1 0
11 C_3 white 1979 2 1 1 0