我有一个数据框,以及与 df 具有相同垂直尺寸的系列,我想分配 该系列到 DataFrame 的所有列。 这样做的自然原因是什么?
例如
df = pd.DataFrame([[1, 2 ], [3, 4], [5 , 6]] )
ser = pd.Series([1, 2, 3 ])
我希望“df”的所有列都等于“ser”。
PS相关:
通过答案解决该问题的一种方法: How to assign dataframe[ boolean Mask] = Series - make it row-wise ? I.e. where Mask = true take values from the same row of the Series (创建所有真实的面具),但我想应该还有更多 简单的方法。
如果我不需要全部,而是某些列 - 答案在这里给出: Assign a Series to several Rows of a Pandas DataFrame
最佳答案
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)
关于python - 将一个系列分配给数据帧的所有列(按列)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46774161/