2017-03-20 8 views
0

私はデータフレームに結合したいパンダの時系列データをたくさん持っています。その結果得られるデータフレームには列名がありません。明示的に指定することなく、データフレーム内のtimeseries(s_a、s_b、s_c、...)の名前を再利用する方法はありますか?パンダの連結:timeseriesの名前を列の名前として自動的に使用する

import pandas as pd 
import numpy as np 

dates = pd.date_range('2017-01-01', '2017-03-01') 
s_a = pd.Series(np.random.randn(60), index = dates) 
s_b = pd.Series(np.random.randn(60), index = dates) 
s_c = pd.Series(np.random.randn(60), index = dates) 
s_d = pd.Series(np.random.randn(60), index = dates) 
df_a = pd.concat([s_a, s_b, s_c, s_d], join='outer', axis = 1) 

私はその後、ライン

s_list = [s_a, s_b, s_c, s_d] 

とデータフレームの建設後に適用される仮想的な機能s_list.namesに沿って何かを期待しています。

df_a = pd.concat(s_list, join='outer', axis = 1) 
df_a.columns = s_list.names() 

は、望ましいデータフレームを生成します。

+1

ハッキーな解決策があります。見て[ここ](https://stackoverflow.com/questions/18425225/getting-the-name-of-a-variable-as-a-string)と[ここ](https://stackoverflow.com/)質問/ 2553354 /どのように変数名を文字列として取得する) – languitar

答えて

1

あなたのシリーズには名前属性がありませんので、連結するときに列名としてうまく流れていく系列に名前を割り当てる必要があると思います。

import pandas as pd 
import numpy as np 

dates = pd.date_range('2017-01-01', '2017-03-01') 
s_a = pd.Series(np.random.randn(60), index = dates,name='s_a') 
s_b = pd.Series(np.random.randn(60), index = dates,name='s_b') 
s_c = pd.Series(np.random.randn(60), index = dates,name='s_c') 
s_d = pd.Series(np.random.randn(60), index = dates,name='s_d') 
s_x = pd.Series(np.random.randn(60), index = dates) 
df_a = pd.concat([s_a, s_b, s_c, s_d],join='outer', axis = 1) 

EDIT: 代替ソリューション

この回答https://stackoverflow.com/a/18425523/5729272に基づいて、リストに名前を取得することができますし、列に割り当てます。

import pandas as pd 
import numpy as np 
import inspect 
def retrieve_name(variables): 
    callers_local_vars = inspect.currentframe().f_back.f_locals.items() 
    return [var_name for var in variables for var_name, var_val in callers_local_vars if var_val is var] 

dates = pd.date_range('2017-01-01', '2017-03-01') 
s_a = pd.Series(np.random.randn(60), index = dates,name='s_a') 
s_b = pd.Series(np.random.randn(60), index = dates,name='s_b') 
s_c = pd.Series(np.random.randn(60), index = dates,name='s_c') 
s_d = pd.Series(np.random.randn(60), index = dates,name='s_d') 
s_x = pd.Series(np.random.randn(60), index = dates) 
df_a = pd.concat([s_a, s_b, s_c, s_d],join='outer', axis = 1) 
df_a.columns = retrieve_name([s_a, s_b, s_c,s_d]) 
df_a.head() 
+0

代わりの解決策は、私が探しているものです。 – Spinor8

関連する問題