2015-12-23 5 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

@クリスこれ。これはおそらくパンダの野生のコードの私の最大の不満です。私は '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) 
関連する問題