2017-10-16 78 views
1

我有一個數據框和一系列與df相同的垂直大小,我想將該系列的 分配給DataFrame的所有列。 爲什麼要這樣做呢?爲dataFrame的所有列指定一個序列(列式)?

例如

df = pd.DataFrame([[1, 2 ], [3, 4], [5 , 6]]) 
ser = pd.Series([1, 2, 3 ]) 

我想 「DF」 的所有列等於 「輯」。

PS相關:

+1

使用'pd.DataFrame({C:SER在DF C ^})'? – Zero

+0

@零謝謝!這樣可行 !我所希望的是,可以爲此目的提供特別的指導 - 例如MatLab中的「repmat」。你不知道嗎? –

回答

1

使用to_framereindex

a = ser.to_frame().reindex(columns=df.columns, method='ffill') 
print (a) 
    0 1 
0 1 1 
1 2 2 
2 3 3 

但它似乎更容易爲comment解決方案,如果需要與實際數據相同的原始列,則添加columns參數:

df = pd.DataFrame({c:ser for c in df.columns}, columns=df.columns) 
+0

非常感謝你!但是,我可以問你,Python中沒有特別的指令,特別是爲了這種目的而構建的嗎?像Matlab中的「repmat」一樣。 –

+1

我想不是,不幸的是:( – jezrael

+0

@AlexanderChervov - 晚餐,現在回答;) – jezrael

1

也許用不同的方式來看待它:

df = pd.concat([ser] * df.shape[1], axis=1) 
相關問題