【问题标题】:How to get first 4 digits from an integer column in python如何从python中的整数列中获取前4位数字
【发布时间】:2021-11-06 03:49:13
【问题描述】:

我正在尝试从整数格式的列中获取月份

'''dvd['yy'] = str(dvd['CalendarYearMonth'])[:3]
dvd['mon'] = str(dvd['CalendarYearMonth'])[4:6]'''

但得到以下输出

   CalendarYearMonth CountryCode  Dividends   yy mon
0             202108          CN      196.0  0     2
1             202109          CN      380.0  0     2
2             202108          IN        NaN  0     2
3             202109          IN      115.0  0     2

谁能帮我获得正确的输出 - dvd 是输入 DF

【问题讨论】:

  • 因为你想要 int 或 sting 作为输出?对于 int,请检查 my answer

标签: python pandas string datetime


【解决方案1】:

试试这个:

dvd['yy'] = dvd['CalendarYearMonth'].astype(str).str[:3]
dvd['mon'] = dvd['CalendarYearMonth'].astype(str).str[4:6]

【讨论】:

  • 感谢它的工作,非常简单,但我不清楚为什么需要第二个 str
  • @Ashish 乐于助人 :P 需要额外的.str 的原因是因为它仍然是熊猫系列,您需要访问 str 访问器:)
【解决方案2】:

试试这个:

dvd = pd.DataFrame( {
    'CalendarYearMonth': [202108.0, 202109.0, 202108.0, 202109.0],

})
dvd['yy'] = dvd['CalendarYearMonth'].apply(lambda x : str(x)[:4])
dvd['mon'] = dvd['CalendarYearMonth'].apply(lambda x : str(x)[4:6])
print(DVD)

输出:

CalendarYearMonth   yy      mon
0   202108.0        2021    08
1   202109.0        2021    09
2   202108.0        2021    08
3   202109.0        2021    09

【讨论】:

    【解决方案3】:

    如果日期已经是 int,请利用它

    df['yy'] = df['CalendarYearMonth']//100
    df['mon'] = df['CalendarYearMonth']-df['yy']*100
    

    输出:

       CalendarYearMonth CountryCode  Dividends    yy  mon
    0             202108          CN      196.0  2021    8
    1             202109          CN      380.0  2021    9
    2             202108          IN        NaN  2021    8
    3             202109          IN      115.0  2021    9
    

    【讨论】:

    • 不知道任何特殊功能的智能方式,我喜欢这样的解决方案
    • 或:dvd['mon'] = dvd['CalendarYearMonth'] % 100
    【解决方案4】:

    要提供更多选项,您可以将包含日期的列转换为日期时间对象,然后提取年份和月份信息:

    import pandas as pd
    
    dvd = pd.DataFrame({
        'CalendarYearMonth': [201908, 202001, 202103, 202107],
    })
    
    dates = pd.to_datetime(dvd['CalendarYearMonth'], format='%Y%m')
    dvd['yy'] = dates.dt.year
    dvd['mon'] = dates.dt.month
    

    它给出:

       CalendarYearMonth    yy  mon
    0             201908  2019    8
    1             202001  2020    1
    2             202103  2021    3
    3             202107  2021    7
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-05
      相关资源
      最近更新 更多