使用python替换date列中缺少的月份和年份

2024-06-01 01:12:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有日期列的数据框,一些基于年和月的数据丢失了。我必须在数据集中显示所有年份的月份,相应的列应该显示为零。在

我的数据框看起来像这样

 Date    Churn    Churnrate  customerID
2008,01  726.0  0.542398        2763
2008,02  345.0  0.257751        1351
2012,11    NaN       NaN           6
2013,01    3.0  0.002241          24
2013,02   10.0  0.007471          34
2013,03   25.0  0.018678          73
2013,04   25.0  0.018678          75
2013,05   14.0  0.010459          61
2013,06   19.0  0.014195          69
2013,07   27.0  0.020172         103
2013,08   22.0  0.016436          79
2013,09   19.0  0.014195          70
2013,10   28.0  0.020919          83
2013,11   22.0  0.016436          78
2013,12   19.0  0.014195          75
2014,01   17.0  0.012701          63
2014,02   21.0  0.015689          55
2014,03    7.0  0.005230          66
2014,04   24.0  0.017931          86
2014,05   18.0  0.013448          90
2014,06   14.0  0.010459          50

例如在2018年,我只有两个月的记录,但我想在相应的列中显示所有带有0的12个月

我的另一个数据帧是这样的

^{pr2}$

我使用了下面给出的相同答案

predicted_retention_rate = predicted_retention_rate.set_index('Months')
idx =(pd.MultiIndex.from_product(predicted_retention_rate.index.str.split('/', expand=True).levels)
        .map('/'.join))

final_retention_rate_predicted = predicted_retention_rate.reindex(idx, fill_value=0).rename_axis('Months').reset_index()
print (final_retention_rate_predicted)

但这项产出中少了几个月

Months  Retention_Rate  Customer_Count
0   2008/01        0.145916             133
1   2008/02        0.924663             762
2   2008/03        0.074544              67
3   2008/07        0.000000               0
4   2008/08        0.000000               0
5   2008/09        0.000000               0
6   2008/10        0.000000               0
7   2008/11        0.000000               0
8   2014/01        0.000000               0
9   2014/02        0.000000               0
10  2014/03        0.000000               0
11  2014/07        0.058684              45
12  2014/08        0.069786              61
13  2014/09        0.076130              64
14  2014/10        0.061856              60
15  2014/11        0.082474              69

请看上面的数据框,2008年包含01、02、03而不是04、05、06,2014年也是如此。我能知道我哪里做错了吗。在


Tags: 数据dateindexratenanfinal年份customerid
2条回答

我认为另一个简单的方法就是这样。在

import pandas as pd
df = pd.DataFrame({"date":["2010-01", "2010-02", "2011-01"], 
                   "a": [1, 2, 3], 
                   "b":[0.2,-0.1,0.4]})
df["date"] = pd.to_datetime(df["date"])
all_dates = pd.DataFrame({"date":pd.date_range(start=df["date"].min(), 
                                               end=df["date"].max(), 
                                               freq="MS")})
df = pd.merge(all_dates, df, how="left", on="date").fillna(0)

如果date是您的索引,那么您可以使用.reset_index()和{}。如果您想保持相同的日期格式,只需添加df["date"] = df["date"].dt.strftime("%Y-%m")

我认为需要^{}^{}Date创建的新index到{}和{}与{}:

df = df.set_index('Date')
idx =(pd.MultiIndex.from_product(df.index.str.split(',', expand=True).levels)
        .map(','.join))

df = df.reindex(idx, fill_value=0).rename_axis('Date').reset_index()
print (df.head())
      Date  Churn  Churnrate  customerID
0  2008,01  726.0   0.542398        2763
1  2008,02  345.0   0.257751        1351
2  2008,03    0.0   0.000000           0
3  2008,04    0.0   0.000000           0
4  2008,05    0.0   0.000000           0

编辑:由range(1,13)定义所有Months的解决方案

^{pr2}$

如果需要,请将缺少的年份和相应的列替换为零:

print (df)
Year   Churn_Count  Churn_Rate  Customer_Count                                        
2008       1071.0    0.800149             4114
2012          0.0    0.000000                6
2013        233.0    0.174075              824
2014        101.0    0.075458              410

然后使用:

df1 = (df.set_index('Year')
        .reindex(range(2008, 2015), fill_value=0)
        .reset_index())
print (df1)
   Year  Churn_Count  Churn_Rate  Customer_Count
0  2008       1071.0    0.800149            4114
1  2009          0.0    0.000000               0
2  2010          0.0    0.000000               0
3  2011          0.0    0.000000               0
4  2012          0.0    0.000000               6
5  2013        233.0    0.174075             824
6  2014        101.0    0.075458             410

reindex最短和最长年份的动态解:

df1 = df.set_index('Year')
df1 = (df1.reindex(range(df1.index.min(), df1.index.max() + 1), fill_value=0)
          .reset_index())
print (df1)
   Year  Churn_Count  Churn_Rate  Customer_Count
0  2008       1071.0    0.800149            4114
1  2009          0.0    0.000000               0
2  2010          0.0    0.000000               0
3  2011          0.0    0.000000               0
4  2012          0.0    0.000000               6
5  2013        233.0    0.174075             824
6  2014        101.0    0.075458             410

相关问题 更多 >