[英]Why can't you assign multiple columns that are not the same name as in the original pandas df?
odds_ft_home_team_win odds_ft_draw odds_ft_away_team_win
0 0.850212 0.100281 0.049506
1 0.081114 0.146371 0.772515
2 0.486790 0.266734 0.246476
3 0.355737 0.301008 0.343255
4 0.294952 0.299490 0.405559
This is a dataframe prob_odds
I want to assign to my previous data-frame df
.这是一个 dataframe
prob_odds
我想分配给我以前的数据帧df
。
df.loc[:,["w","d","a"]]=prob_odds
As you can see I want the new columns to have a different name than in the original dataframe.如您所见,我希望新列的名称与原始 dataframe 中的名称不同。 This returns a data-frame that has the columns
"w","d","a"
with NA values.这将返回一个数据框,其中包含具有 NA 值
"w","d","a"
列。 If I change the names of the columns in the prob_odds
Data-Frame to match the names in the df
the assignment works.如果我更改
prob_odds
数据帧中列的名称以匹配df
中的名称,则分配有效。 Why is that?这是为什么? What is the way to go around this so that you can assign new columns without having to rename the old ones beforehand.
go 的方法是什么,这样您就可以分配新列而不必事先重命名旧列。
You can, just without .loc
(because .loc
would search for existing indexes and columns to operate on):你可以,只是没有
.loc
(因为.loc
会搜索现有的索引和列进行操作):
N = 10
df = pd.DataFrame({'a': 1 * np.ones(N), 'b': 2 * np.ones(N)})
df[['c', 'd']] = pd.DataFrame({'x': 3 * np.ones(N), 'y': 4 * np.ones(N)})
df
Output: Output:
a b c d
0 1.0 2.0 3.0 4.0
1 1.0 2.0 3.0 4.0
2 1.0 2.0 3.0 4.0
3 1.0 2.0 3.0 4.0
4 1.0 2.0 3.0 4.0
5 1.0 2.0 3.0 4.0
6 1.0 2.0 3.0 4.0
7 1.0 2.0 3.0 4.0
8 1.0 2.0 3.0 4.0
9 1.0 2.0 3.0 4.0
PS To match your naming, df[["w","d","a"]] = prob_odds
should work PS为了匹配您的命名,
df[["w","d","a"]] = prob_odds
应该可以工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.