【问题标题】:Separation of year, month and day in an 8-digit number用 8 位数字分隔年、月和日
【发布时间】:2021-11-21 12:11:14
【问题描述】:

我是 Python/pandas 的新手。 我有一个看起来像这样的数据框

x = pd.DataFrame([20210901,20210902, 20210903, 20210904])

[出]:

          0
0  20210901
1  20210902
2  20210903
3  20210904

我想将每一行分开如下:例如

year = 2021
month = 9
day = 1

或者我有一个这样的每一行的列表:

[2021,9,1]

【问题讨论】:

  • 你要的输出是什么?请添加您想要的方式,以便我们可以看到您寻求的结果是什么

标签: python pandas dataframe date


【解决方案1】:

您可以使用pd.to_datetime 将整列转换为datetime 类型。

>>> import pandas as pd
>>>
>>> df = pd.DataFrame({'Col': [20210917,20210918, 20210919, 20210920]})
>>>
>>> df.Col = pd.to_datetime(df.Col, format='%Y%m%d')
>>> df
         Col
0 2021-09-17
1 2021-09-18
2 2021-09-19
3 2021-09-20
>>> df['Year'] = df.Col.dt.year
>>> df['Month'] = df.Col.dt.month
>>> df['Day'] = df.Col.dt.day
>>>
>>> df
         Col  Year  Month  Day
0 2021-09-17  2021      9   17
1 2021-09-18  2021      9   18
2 2021-09-19  2021      9   19
3 2021-09-20  2021      9   20

如果您希望结果为列表,您可以使用列表推导和zip 函数。

>>> [(year, month, day) for year, month, day in zip(df.Year, df.Month, df.Day)]
[(2021, 9, 17), (2021, 9, 18), (2021, 9, 19), (2021, 9, 20)]

【讨论】:

    【解决方案2】:

    将每一行分隔成如下三个新列:年、月、日

    import pandas as pd
    
    df = pd.DataFrame({"date":[20210901,20210902, 20210903, 20210904]})
    
    # split date field to three fields: year month day 
    df["year"] = df["date"].apply(lambda x: str(x)[:4])
    df["month"] = df["date"].apply(lambda x: str(x)[4:6])
    df["day"] = df["date"].apply(lambda x: str(x)[6:])
    
    print(df)
    

    结果如下

    # result is:
     date  year  month  day
    0  20210901  2021    09  01
    1  20210902  2021    09  02
    2  20210903  2021    09  03
    3  20210904  2021    09  04
    

    【讨论】:

      【解决方案3】:

      我创建了一个简单的函数,它将以您想要的格式返回一个压缩列表

      def convert_to_dates(df):
               dates = []
               for i,v in x.iterrows():
                   dates.append(v.values[0])
               for i in range(len(dates)):
                   dates[i] = str(dates[i])
               years = []
               months = []
               days = []
               for i in range(len(dates)):
                   years.append(dates[i][0:4])
                   months.append(dates[i][4:6])
                   days.append(dates[i][6:8])
               return list(zip(years, months, days))
      

      使用convert_to_dates(x) 调用它

      输出:

      In [4]: convert_to_dates(x)
      Out[4]:
      [('2021', '09', '01'),
       ('2021', '09', '02'),
       ('2021', '09', '03'),
       ('2021', '09', '04')]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-17
        • 2017-07-13
        相关资源
        最近更新 更多