[問題] 關於 assign series to dataframe

作者: os653   2018-11-13 19:58:45
>>> df = pd.DataFrame([[1,2],[3,4],[5,6]])
>>> df
0 1
0 1 2
1 3 4
2 5 6
>>> selected_df = df.loc[[0,2]]
>>> selected_df
0 1
0 1 2
2 5 6
>>> selected_df.loc[:, 'assign_by_series'] = pd.Series([100, 200])
>>> selected_df
0 1 assign_by_series
0 1 2 100.0
2 5 6 NaN
>>> selected_df.loc[:, 'assign_by_list'] = [100, 200]
>>> selected_df
0 1 assign_by_series assign_by_list
0 1 2 100.0 100
2 5 6 NaN 200
示意如上
assign series 時,資料被依照 index 存了
又因為 series 只有兩筆資料,所以 selected_df 的第三筆變成 NaN
而 list 不會有這問題
請問這是正常的嗎?因為蠻容易不小心手殘寫錯

Links booklink

Contact Us: admin [ a t ] ucptt.com