问题
I have a pandas series that looks like this:
>>> myseries
2012-01-01 15:20:00-05:00 2
2012-01-01 15:30:00-05:00 1
2012-01-01 15:40:00-05:00 0
...
And I try to put it into a dataframe as so:
>>> mydf = pd.DataFrame(myseries, columns=["myseries"], index = myseries.index)
and all the values become NaN for some reason:
>>> mydf
2012-01-01 15:20:00-05:00 NaN
2012-01-01 15:30:00-05:00 NaN
2012-01-01 15:40:00-05:00 NaN
I'm pretty confused. This seems like a really simple application. What am I doing wrong? By the way, replacing with pd.DataFrame(myseries.values, columns=...)
fixes the problem, but why is it necessary? Thank you.
回答1:
s = pd.Series([0,1,2,3], index=pd.date_range('2014-01-01', periods=4))
df = pd.DataFrame(s, columns=['s'], index=s.index)
print(df)
yields
s
2014-01-01 0
2014-01-02 1
2014-01-03 2
2014-01-04 3
回答2:
Even simpler:
s = pd.Series([0,1,2,3], index=pd.date_range('2014-01-01', periods=4), name='s')
df = pd.DataFrame(s)
print(df)
yields
s
2014-01-01 0
2014-01-02 1
2014-01-03 2
2014-01-04 3
来源:https://stackoverflow.com/questions/28934992/when-i-insert-pandas-series-into-dataframe-all-values-become-nan