2015-12-23 14 views
5

我有一个数据框与时间戳列和数字列。如果时间戳列是时区天真的,我可以追加一个新行。如何在具有时区感知的时间戳列的数据框上追加?

df = pd.DataFrame([[1,2],[3,4]], columns=['timestamp', 'number']) 
df['timestamp']=pd.to_datetime(df['timestamp']) 
df 
#      timestamp number 
# 0 1970-01-01 00:00:00.000000001  2 
# 1 1970-01-01 00:00:00.000000003  4 

df.append(df.loc[0]) 
#      timestamp number 
# 0 1970-01-01 00:00:00.000000001  2 
# 1 1970-01-01 00:00:00.000000003  4 
# 0 1970-01-01 00:00:00.000000001  2 

但如果我设置时区为时间戳列,然后尝试添加新行,我得到的错误。

df['timestamp']=df['timestamp'].apply(lambda x: x.tz_localize('utc')) 
df 
#        timestamp number 
# 0 1970-01-01 00:00:00.000000001+00:00  2 
# 1 1970-01-01 00:00:00.000000003+00:00  4 
df.append(df.loc[0]) 
# Traceback (most recent call last): 
# File "<stdin>", line 1, in <module> 
# File "/Library/Python/2.7/site-packages/pandas-0.17.1-py2.7-macosx-10.10-intel.egg/pandas/core/frame.py", line 4231, in append 
#  verify_integrity=verify_integrity) 
# File "/Library/Python/2.7/site-packages/pandas-0.17.1-py2.7-macosx-10.10-intel.egg/pandas/tools/merge.py", line 813, in concat 
#  return op.get_result() 
# File "/Library/Python/2.7/site-packages/pandas-0.17.1-py2.7-macosx-10.10-intel.egg/pandas/tools/merge.py", line 995, in get_result 
#  mgrs_indexers, self.new_axes, concat_axis=self.axis, copy=self.copy) 
# File "/Library/Python/2.7/site-packages/pandas-0.17.1-py2.7-macosx-10.10-intel.egg/pandas/core/internals.py", line 4456, in concatenate_block_managers 
#  for placement, join_units in concat_plan] 
# File "/Library/Python/2.7/site-packages/pandas-0.17.1-py2.7-macosx-10.10-intel.egg/pandas/core/internals.py", line 4561, in concatenate_join_units 
#  concat_values = com._concat_compat(to_concat, axis=concat_axis) 
# File "/Library/Python/2.7/site-packages/pandas-0.17.1-py2.7-macosx-10.10-intel.egg/pandas/core/common.py", line 2548, in _concat_compat 
#  return _concat_compat(to_concat, axis=axis) 
# File "/Library/Python/2.7/site-packages/pandas-0.17.1-py2.7-macosx-10.10-intel.egg/pandas/tseries/common.py", line 256, in _concat_compat 
#  return DatetimeIndex(np.concatenate([ x.tz_localize(None).asi8 for x in to_concat ]), tz=list(tzs)[0]) 
# AttributeError: 'numpy.ndarray' object has no attribute 'tz_localize' 

我如何能新行追加到具有时区意识到timespamp列中的数据帧的任何帮助,将不胜感激。

+0

什么是您的熊猫版本。我可以在0.16.1中运行这个例子。顺便说一句,而不是应用(pd.to_datetime),只需执行pd.to_datetime(df)即可。这行:df [0] = df [0] .apply(pd.to_datetime)也似乎是错误的,似乎你想要df ['timestamp'] = df ['timestamp']。 。 – Chris

+0

@Chris这。这可能是我对熊猫野生代码最大的抱怨。我已经看到过这样的东西:'df.apply(lambda x:x.sum())'并且更糟。 :/ –

+0

@Chris,谢谢你指出问题中的错误。我正在使用熊猫版本0.17.1。 – yadu

回答

1

这是熊猫版本中的一个错误(贷记到this answer)。 正如他们所述,您的解决方案可能是:

df = df.astype(str).append(df.loc[0].astype(str)) 
df['timestamp'] = pd.to_datetime(df['timestamp'], utc=True) 
相关问题