【问题标题】:Pandas Time Series shows NaN after converting entries to floatPandas 时间序列在将条目转换为浮点数后显示 NaN
【发布时间】:2019-01-19 05:25:50
【问题描述】:

我正在尝试从数据框中获取时间序列。我的数据框包含两个所需的列 - 时间戳和速度。到目前为止,这是我的代码:

第 1 步:我将所需速度列中的所有空格替换为 0

bus1354['Speed'].replace('   ',0,inplace=True)

第 2 步:然后我检查在此之后的 Speed 列中是否有任何 NaN 值

assert not bus1354['Speed'].isnull().any()

第 3 步:然后我检查数据帧中 Timestamp 和 Speed 列的前几个条目

bus1354[['Timestamp','Speed']].head()

这是我得到的结果(到目前为止还不错):

第 4 步:然后我截断时间戳以便仅显示 hh:mm:ss 并删除毫秒。我也转换为日期时间格式。

bus1354['Timestamp'] = pd.to_datetime(bus1354['Timestamp'].apply(lambda x : x[:7]))

第 5 步:我检查截断的结果

bus1354['Timestamp'].head()

看起来是这样的:

第6步:然后我将速度从非空对象转换为float64

bus1354['Speed'] = bus1354['Speed'].apply(float)

第 7 步:创建时间范围和时间序列

bstimeRng = bus1354['Timestamp']
bs1354Ser = pd.Series(bus1354['Speed'], index=bstimeRng)

第 8 步:然而,一旦我输出了我的时间序列,我的 Speed 列就会得到一堆 NaN。

bs1354Ser

我仍在学习熊猫的来龙去脉,如果这听起来像是一个基本问题,请多多包涵。为什么即使我将 Speed 列更改为 float64 后,时间序列仍将我想要的 Speed 值显示为“NaN”?

【问题讨论】:

    标签: python pandas jupyter


    【解决方案1】:

    这里最好使用set_index:

    s1354Ser = bus1354.set_index('Timestamp')['Speed']
    

    示例

    bus1354 = pd.DataFrame(
            {'Timestamp':['08:38:00:009','08:38:00:013','08:38:00:019'],
            'Speed':[42,42,43]})
    
    
    print (bus1354)
          Timestamp  Speed
    0  08:38:00:009     42
    1  08:38:00:013     42
    2  08:38:00:019     43
    
    bus1354['Timestamp'] = pd.to_datetime(bus1354['Timestamp'].str[:7])
    bus1354['Speed'] = bus1354['Speed'].astype(float)
    
    s1354Ser = bus1354.set_index('Timestamp')['Speed']
    print (s1354Ser)
    Timestamp
    2019-01-19 08:38:00    42.0
    2019-01-19 08:38:00    42.0
    2019-01-19 08:38:00    43.0
    Name: Speed, dtype: float64
    

    解决方案中的缺失值是问题数据对齐:

    #sample data
    df = pd.DataFrame(
            {'a':[0,2,3],
             'b':[41,42,43]})
    
    
    print (df)
       a   b
    0  0  41
    1  2  42
    2  3  43
    

    如果检查原始数据的索引:

    print (df.index.tolist())
    [0, 1, 2]
    

    a 列的值用于新索引:

    print (df['a'].tolist())
    [0, 2, 3]
    

    如果可能,Series 构造函数对齐数据 - 来自原始的旧索引与来自a 列的新索引,如果值不存在则创建NaNs:

    s = pd.Series(df['b'], index=df['a'])
    print (s)
    a
    0    41.0 <-align by 0 from original index
    2    43.0 <-align by 2 from original index
    3     NaN <- not exist 3, so NaN
    Name: b, dtype: float64
    

    但是如果将Speed 的值通过values 转换为numpy 1d 数组,则数组没有像Series 这样的索引:

    s1354Ser = pd.Series(bus1354['Speed'].values, index=bstimeRng)
    
    s = pd.Series(df['b'].values, index=df['a'])
    print (s)
    a
    0    41
    2    42
    3    43
    dtype: int64
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-15
      • 1970-01-01
      • 2017-03-20
      • 2021-11-16
      • 2020-07-02
      • 1970-01-01
      • 2018-12-23
      相关资源
      最近更新 更多