Python, Pandas: Replacing Values In One Df By Same-index Values From Another Df
I have two data frames with exactly the same index: the first one: 0 1 2 2 0.011765 0.490196 0.015686 2 0.011765 0.490196 0.015686 2 0.007843
Solution 1:
Use the index of the second dataframe to slice the first one and then assign.
df1.loc[df2.index] = df2
Solution 2:
You can use merge
empty dataframe df1
with df2
by indexes:
print pd.merge(df1[[]], df2, left_index=True, right_index=True)
01200.0558520.1181380.05238600.0558520.1181380.05238600.0558520.1181380.05238600.0558520.1181380.05238620.0963940.6356410.06852420.0963940.6356410.06852420.0963940.6356410.06852420.0963940.6356410.06852420.0963940.6356410.068524
Or join
:
print df1[[]].join(df2)
01200.0558520.1181380.05238600.0558520.1181380.05238600.0558520.1181380.05238600.0558520.1181380.05238620.0963940.6356410.06852420.0963940.6356410.06852420.0963940.6356410.06852420.0963940.6356410.06852420.0963940.6356410.068524
If you need preserved index ordering use merge with reset_index
, merge
on column index
and then set_index
:
df = pd.merge(df1[[]].reset_index(), df2.reset_index(), on='index').set_index('index')
df.index.name = None
print df
01220.0963940.6356410.06852420.0963940.6356410.06852420.0963940.6356410.06852420.0963940.6356410.06852420.0963940.6356410.06852400.0558520.1181380.05238600.0558520.1181380.05238600.0558520.1181380.05238600.0558520.1181380.052386
Post a Comment for "Python, Pandas: Replacing Values In One Df By Same-index Values From Another Df"