pandas.Series()使用DataFrame Columns创建返回NaN数据条目

nls*_*bch 7 python time-series dataframe python-3.x pandas

我试图使用简化的代码将数据帧转换为一个系列,如下所示:

dates = ['2016-1-{}'.format(i)for i in range(1,21)]
values = [i for i in range(20)]
data = {'Date': dates, 'Value': values}
df = pd.DataFrame(data)
df['Date'] = pd.to_datetime(df['Date'])
ts = pd.Series(df['Value'], index=df['Date'])
print(ts)
Run Code Online (Sandbox Code Playgroud)

但是,打印输出如下所示:

Date
2016-01-01   NaN
2016-01-02   NaN
2016-01-03   NaN
2016-01-04   NaN
2016-01-05   NaN
2016-01-06   NaN
2016-01-07   NaN
2016-01-08   NaN
2016-01-09   NaN
2016-01-10   NaN
2016-01-11   NaN
2016-01-12   NaN
2016-01-13   NaN
2016-01-14   NaN
2016-01-15   NaN
2016-01-16   NaN
2016-01-17   NaN
2016-01-18   NaN
2016-01-19   NaN
2016-01-20   NaN
Name: Value, dtype: float64
Run Code Online (Sandbox Code Playgroud)

哪里NaN来的?DataFrame对象的视图不是Series该类的有效输入吗?

我已经找到了to_series函数pd.Index对象,是有类似的东西DataFrameS'

jez*_*ael 20

我想你可以使用values,它将列转换Value为数组:

ts = pd.Series(df['Value'].values, index=df['Date'])
Run Code Online (Sandbox Code Playgroud)
import pandas as pd
import numpy as np
import io

dates = ['2016-1-{}'.format(i)for i in range(1,21)]
values = [i for i in range(20)]
data = {'Date': dates, 'Value': values}
df = pd.DataFrame(data)
df['Date'] = pd.to_datetime(df['Date'])
print df['Value'].values
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19]

ts = pd.Series(df['Value'].values, index=df['Date'])
Run Code Online (Sandbox Code Playgroud)
print(ts)
Date
2016-01-01     0
2016-01-02     1
2016-01-03     2
2016-01-04     3
2016-01-05     4
2016-01-06     5
2016-01-07     6
2016-01-08     7
2016-01-09     8
2016-01-10     9
2016-01-11    10
2016-01-12    11
2016-01-13    12
2016-01-14    13
2016-01-15    14
2016-01-16    15
2016-01-17    16
2016-01-18    17
2016-01-19    18
2016-01-20    19
dtype: int64
Run Code Online (Sandbox Code Playgroud)

或者您可以使用:

ts1 = pd.Series(data=values, index=pd.to_datetime(dates))
print(ts1)
2016-01-01     0
2016-01-02     1
2016-01-03     2
2016-01-04     3
2016-01-05     4
2016-01-06     5
2016-01-07     6
2016-01-08     7
2016-01-09     8
2016-01-10     9
2016-01-11    10
2016-01-12    11
2016-01-13    12
2016-01-14    13
2016-01-15    14
2016-01-16    15
2016-01-17    16
2016-01-18    17
2016-01-19    18
2016-01-20    19
dtype: int64
Run Code Online (Sandbox Code Playgroud)

谢谢你@ajcr更好的解释为什么你得到NaN:

当您给一个Series或一个DataFrame列时pd.Series,它将使用index您指定的重新索引它.由于您的DataFrame列具有整数index(而不是a date index),因此您会获得大量缺失值.

  • @ j4ck:当你将一个Series或DataFrame列赋予`pd.Series`时,它将使用你指定的索引重新索引它.由于您的DataFrame列具有整数索引(不是日期索引).你会得到很多缺失值. (2认同)