简体   繁体   English

在大熊猫中使用周的所有可能值创建 DF

[英]create DF with all possible values for week in pandas

I have a dataframe that looks like this我有一个看起来像这样的数据框

id    week count
1       1    2
1       2    2
2       3    1
3       5    4

I want a df that will have each id with all the possible values of week (1-5):我想要一个 df ,它的每个 id 都有周(1-5)的所有可能值:

id    week  count
1       1     2
1       2     2
1       3     null
1       4     null
1       5     null

I would just create a new dataframe with all id values repeated 5 times, and the range of 1-5 repeated n times, n being the number of id values.我只想创建一个新的数据框,其中所有id值重复 5 次,1-5 的范围重复n次, nid值的数量。 Then, do an outer merge with your original dataframe:然后,与原始数据框进行外部合并:

new_df = (pd.merge(pd.DataFrame({'id':np.repeat(df['id'].unique(), 5),
                                 'week':np.tile([1,2,3,4,5], df['id'].nunique())}),
                   df, how='outer'))

    id  week  count
0    1     1    2.0
1    1     2    2.0
2    1     3    NaN
3    1     4    NaN
4    1     5    NaN
5    2     1    NaN
6    2     2    NaN
7    2     3    1.0
8    2     4    NaN
9    2     5    NaN
10   3     1    NaN
11   3     2    NaN
12   3     3    NaN
13   3     4    NaN
14   3     5    4.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM