Skip to content Skip to sidebar Skip to footer

Python Pandas How To Copy Column Values Regarding An Index Column

Note: the question was edited and extended as it originally lacked precision. The first example introduces the question, but should only be considered as an introduction Having two

Solution 1:

use reindex

In [142]:
df1.reindex(df2.index)

Out[142]:
     value  other_columns
idx                      
1      7.0            NaN
2      6.0            NaN
4      NaN            NaN

reindex_like also works:

In [143]:
df1.reindex_like(df2)

Out[143]:
     value  ...other_columns
idx                         
1      7.0               NaN
2      6.0               NaN
4      NaN               NaN

Or label-based index using loc:

In [144]:
df1.loc[df2.index]

Out[144]:
     value  other_columns
idx                      
1      7.0            NaN
2      6.0            NaN
4      NaN            NaN

If idx is really a column, then you need to call set_index first and then doc any of the above:

In [148]:
df1.set_index('idx').reindex(df2.set_index('idx').index).reset_index()

Out[148]:
   idx  value  other_columns
0    1    7.0            NaN
1    2    6.0            NaN
2    4    NaN            NaN

Solution 2:

I think you should use the merge function of panda :

data = panda.merge(dataframe1, dataframe2, on="idx", how="right")

The result you want will be the first column.

See the doc for more one the how parameter (set NaN, or take only left, right or both ...).

See ya !

EDIT :

I saw your edit and you wonder how to extract only the columns you want, but you just have to pass the columns you want to the merge :

data = panda.merge(df1[['idx', 'val']], df2.drop('val', axis=1), on="idx", how="right")

(don't worry, the drop command won't delete the column of df2, it will return a DataFrame without with column)


Post a Comment for "Python Pandas How To Copy Column Values Regarding An Index Column"