0

I'm trying to merge the values of columns (Columns B and C) within the same dataframe. B and C sometimes have the same values. Some values in B are present in C while some values in C are present in B. The final results would show one column that is the combination of the two columns.

Initial data:

 A          B          C            D
Apple    Canada        ''          RED
Bananas    ''          Germany     BLUE
Carrot     US          US          GREEN
Dorito     ''          ''          INDIGO

Expected Data:

 A          B         C
Apple    Canada      RED
Bananas  Germany      BLUE
Carrot     US        GREEN
Dorito     ''        INDIGO
1
  • 3
    What if B and C had different values? Commented May 7, 2019 at 17:25

3 Answers 3

2

IIUC

df['B']=df[['B','C']].replace("''",np.nan).bfill(1).loc[:,'B']
df=df.drop('C',1).rename(columns={'D':'C'})
df
Out[102]: 
         A        B       C
0    Apple   Canada     RED
1  Bananas  Germany    BLUE
2   Carrot       US   GREEN
3   Dorito      NaN  INDIGO
Sign up to request clarification or add additional context in comments.

Comments

1

You can sort strings and take the last one:

df['B'] = df[['B', 'C']].apply(lambda x: x.sort_values()[1], axis=1)

df=df.drop('C', 1).rename(columns={'D':'C'})    
print(df)

Output:

         A        B       C
0    Apple   Canada     RED
1  Bananas  Germany    BLUE
2   Carrot       US   GREEN
3   Dorito       ''  INDIGO

Comments

0

Another way would be to make smart use of list comprehension:

# Make sets of the column B and C combined to get rid of duplicates
k = [set(b.strip() for b in a) for a in zip(df['B'], df['C'])]

# Flatten sets to strings
k = [''.join(x) for x in k]

# Create desired column
df['B'] = k
df.drop('C', axis=1, inplace=True)

print(df)
         A        B       D
0    Apple   Canada     RED
1  Bananas  Germany    BLUE
2   Carrot       US   GREEN
3   Dorito           INDIGO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.