-4

I'm trying to merge 2 columns in python: both column A and column B contains names of states. I'd love to merge column An and column B to get the "Ideal Result" column. How can i achieve it in python? Thanks a lot! And this is in Python; they are dataframes.

enter image description here

S.J
  • 109
  • 2
  • 3
  • 11
  • 7
    What kind of column are we talking about? A spreadsheet column? A dataframe column? A column in a nested list? – Aran-Fey Oct 10 '18 at 13:49
  • something with `row[0] or row[1]` maybe? we need to see your input & some code if possible – Jean-François Fabre Oct 10 '18 at 13:54
  • sorry i wasn't being clear. they are dataframe columns in python. – S.J Oct 10 '18 at 13:54
  • 1
    Possible duplicate of [Pandas groupby: How to get a union of strings](https://stackoverflow.com/questions/17841149/pandas-groupby-how-to-get-a-union-of-strings) – msi_gerva Oct 10 '18 at 13:57
  • If they are object types you can just concat them `df.A+df.B` – mad_ Oct 10 '18 at 13:59
  • Assuming you want to use Python to modify an Excel file. Take a look at https://www.xlwings.org/ this is a simple but powerful python library to modify Excel files. – James McCorrie Oct 10 '18 at 14:08

3 Answers3

1

If it is a dataframe, I think you could try to use np.where:

df['idealcol'] = np.where(df['A'].isnull(), df['B'] , df['A'])
IonicSolutions
  • 2,559
  • 1
  • 18
  • 31
priya
  • 46
  • 4
0

Considering this is in some excel in a dataframe df:

df['Ideal Result'] = df.A.str.cat(df.B)   

If not:

import pandas as pd
df = pd.read_csv("\\your_csv.csv")
Rahul Agarwal
  • 4,034
  • 7
  • 27
  • 51
0

Use np.where is check if string in column A is null or empty

import pandas as pd
import numpy as np
df=pd.DataFrame({'A':['AL',''],'B':['','BL']})
df['ideal_col']=np.where((df['A']=='') |( df['A'].isnull()), np.where(df['B'].isnull(),'',df['B']) , df['A'])
mad_
  • 8,121
  • 2
  • 25
  • 40