Skip to content Skip to sidebar Skip to footer

Replace Df Index Values With Values From A List But Ignore Empty Strings

I want to replace DF1.index.values with DF2[some_column].values HOWEVER i only want to replace if DF2[some_column].value is not null or empty string. DF1.index.values Index(['a',

Solution 1:

You can use where to choose values by the condition from to sources:

DF1.index = DF2[some_column].where(DF2[some_column]!="", DF2.index)

So it will use DF2[some_column] values if DF2[some_column]!="" (in fact here we create a Series which is used as boolean index saying what data to choose for each raw), in the other case it will use DF2.index value.

As you don't want nan values also, you need pd.notnull functions. And to check both conditions use "logical and" function for pairs of values in two Series which is &.

So the final code is

DF1.index = DF2[some_column].where(
           (DF2[some_column]!="") & pd.notnull(DF2[some_column]), DF2.index)

Post a Comment for "Replace Df Index Values With Values From A List But Ignore Empty Strings"