代码之家  ›  专栏  ›  技术社区  ›  Starbucks

串联列对象,缺少零

  •  0
  • Starbucks  · 技术社区  · 6 年前

    我试图连接两列-一小时(hh)和分钟(mm)列。有些值是双零。连接小时和分钟列时,不包括小时列。任何帮助都将不胜感激。

    import pandas as pd
    from urllib.request import urlopen
    import datetime as dt
    
    url = "https://www.ndbc.noaa.gov/view_text_file.php?filename=42887h2014.txt.gz&dir=data/historical/stdmet/"
    data_csv = urlopen(url)
    df = pd.read_csv(data_csv, delim_whitespace=True, index_col=0, parse_dates=True)
    
    #Reset Index + remove first row + rename column
    df.reset_index(level=0, inplace=True)
    df = df.iloc[1:]
    df = df.rename(columns={'#YY': 'YY'})
    
    df['Time'] = df[df.columns[3:5]].apply(lambda x: ':'.join(x.dropna().astype(int).astype(str)),axis=1)
    

    结果:

    Out[203]: 
    1          0:0
    2         0:20
    3         0:40
    4          1:0
    5         1:20
    

    应该是:

    Out[203]: 
    1         00:00
    2         00:20
    3         00:40
    4         01:00
    5         01:20
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   gofvonx    6 年前

    你可以用 str.cat apply

    df[df.columns[4]].str.cat(df[df.columns[5]], sep=':')