[英]Can we insert values of one column from one data frame to another column of another dataframe based on index using python?
Sorry If my English is bad(while trying to explain).对不起,如果我的英语不好(试图解释)。 I have two different data frames.
我有两个不同的数据框。 Say my df1 is,
说我的 df1 是,
a b d
0 1 2 5
1 2 3 9
2 3 4 1
3 1 2 5
4 2 3 9
5 3 4 1
6 1 2 5
7 2 3 9
8 3 4 1
Second df is,第二个df是,
xyz
0 23
1 24
2 35
6 17
7 23
8 34
Now, I only want to replace the values in my df1(column 'a') based on the index of df2.suppose index 0 of df2 has 23 then df1 index 0 has to be changed to 23. I have tried it but I am getting an error.现在,我只想根据 df2 的索引替换 df1(column 'a') 中的值。假设 df2 的索引 0 有 23,然后 df1 索引 0 必须更改为 23。我已经尝试过了,但我是收到错误。 How do I replace the values.
如何替换这些值。 My code is below:-
我的代码如下: -
for i in df1.index:
for j indf2.index:
if i == j:
df1.iloc['a'][i] = df2.loc['xyz'][j]
print(df1)
getting a error like收到类似的错误
KeyError: 'xyz'
During handling of the above exception, another exception occurred:
How would I resolve this, Where am I going wrong?
Output will like this: Output 会像这样:
a b d
0 23 2 5
1 24 3 9
2 35 4 1
3 1 2 5
4 2 3 9
5 3 4 1
6 17 2 5
7 23 3 9
8 34 4 1
Does this help Rapooram?这对拉普拉姆有帮助吗?
df = pd.DataFrame({'a' : [1,2,3,1,2,3,1,2,3],
'b' : [2,3,4,2,3,4,2,3,4],
'd' : [5,9,1,5,9,1,5,9,1]})
df2 = pd.DataFrame({'index' : [0,1,2,6,7,8] ,
'xyz' : [23,24,35,17,23,43]})
df2.set_index('index',inplace=True)
df.loc[df2.index,['a']] = df2.xyz
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.