0

I have this dataframe with two column['c1','c2'], and I want to fill c2 with its corresponding c1 if exist, also if c1 already have a value keep it don't change it with c2. Here is an example:

input

c1             c2
HP_0003470  
HP_8362789    HP_0093723
              MP_0000231
              MP_0000231

output

c1             c2
HP_0003470  
HP_8362789    HP_0093723
MP_0000231    MP_0000231
MP_0000231    MP_0000231

It's look easy, but I'm beginner in python :( Any help please.

LamaMo
  • 576
  • 2
  • 8
  • 19
  • 3
    Are the empty rows, blanks strings `''`or `NAN`s? – Zero Jul 18 '18 at 18:47
  • @Zero it's empty string ' ' – LamaMo Jul 18 '18 at 18:53
  • @ScottBoston I don't understand what you mean ? – LamaMo Jul 18 '18 at 18:54
  • Use `df.loc[df['c1'].eq(''), 'c1'] = df['c2']` – Zero Jul 18 '18 at 18:55
  • @SaraWasl, It's difficult to tell exactly what your DataFrame values are when you just paste a DataFrame with empty values or missing values. Using `df.to_dict()` will yield: `{'c1': {0: 'HP_0003470', 1: 'MP_0000231', 2: '', 3: ''},...` making it clear how they are truly represented. – ALollz Jul 18 '18 at 18:58

1 Answers1

1

You can do so:

df['c1'] = df['c1'].replace('',np.NaN).fillna(df['c2'])
df['c2'] = df['c2'].replace('',np.NaN).fillna(df['c1'])

Output:

           c1          c2
0  HP_0003470  HP_0003470
1  HP_8362789  HP_0093723
2  MP_0000231  MP_0000231
3  MP_0000231  MP_0000231
Joe
  • 12,057
  • 5
  • 39
  • 55