我有一个数据框,以及与 df 相同垂直尺寸的系列,我想分配
该系列到 DataFrame 的所有列。
自然又是什么原因呢?
例如
df = pd.DataFrame([[1, 2 ], [3, 4], [5 , 6]] )
ser = pd.Series([1, 2, 3 ])
我希望“df”的所有列都等于“ser”。
PS相关:
通过答案解决它的一种方法:如何分配 dataframe[ boolean Mask] = Series - 使其按行排列? IE。其中 Mask = true 从系列的同一行获取值 https://stackoverflow.com/questions/46766416/how-to-assign-dataframe-boolean-mask-series-make-it-row-wise-i-e-where/46766472?noredirect=1#comment80478418_46766472(创建所有真实的面具),但我想应该还有更多
简单的方法。
如果我不需要全部,而是某些列 - 答案在这里给出:将一个系列分配给 Pandas DataFrame 的几行 https://stackoverflow.com/questions/44806006/assign-a-series-to-several-rows-of-a-pandas-dataframe
Use to_frame http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.to_frame.html with reindex http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html:
a = ser.to_frame().reindex(columns=df.columns, method='ffill')
print (a)
0 1
0 1 1
1 2 2
2 3 3
但解决方案似乎更容易comment https://stackoverflow.com/questions/46774161/assign-a-series-to-all-columns-of-the-dataframe-columnwise/46774324#comment80494066_46774161,添加了columns
如果需要与原始真实数据相同的顺序列,则参数:
df = pd.DataFrame({c:ser for c in df.columns}, columns=df.columns)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)