-1

I'm trying to merge two columns. Merging is not working out and I've been reading and asking questions for two days trying to find a solution so I'm going to go a different route.
Since I have to change the column name after I merge anyway why not just create a new column and fill it based on the other two.
So I have column A, B and C now.
C is a blank column.
Column A has values for most rows but not all, In the case that column A doesn't have a value I want to use Column B's value. I want to put one of the two Values in column C.

Please keep in mind that when column A doesn't have a value a "-" was put in its place (hence why I'm having a horrendous time trying to merge these columns). I have converted the "-" to NaN but then the .fillna function doesn't work and I'm not sure why.

I'm thinking I have to write a for loop and an if statement to accomplish this although I feel like there is a function that would accomplish compiling a new column based on the other two columns values.

| A  | B  |
| 34 | 35 |
| 37 | -  |
| -  | 32 |
| 94 | 92 |
| -  | 91 |
| 47 | -  |

Desired Result

|C |
|34|
|37|
|32|
|94|
|91|
|47|
  • Does this answer your question? [Pandas: To create a new column based on two column values](https://stackoverflow.com/questions/53405453/pandas-to-create-a-new-column-based-on-two-column-values) – Trenton McKinney Jun 11 '20 at 15:32

2 Answers2

3

Does this answer your question:

df['A']=df.apply(lambda x: x['B'] if x['A']=='-' else x['A'],axis=1) 
Raghul Raj
  • 1,428
  • 9
  • 24
  • The issue is the cell values aren't na they have a "-" in them. This yields the same result I had before. – Russell Comer Jun 11 '20 at 17:50
  • I thought you already did that when you said this "I have converted the "-" to NaN". I'll update my answer now accordingly. – Raghul Raj Jun 11 '20 at 17:55
  • So I tried the updated code, then I went back to the previous code you had there and ran this above the lamda. combined_df = combined_df.replace('-', np.NaN) it had the result of NaN in the column instead of '-' – Russell Comer Jun 11 '20 at 18:07
  • I'm sorry I don't understand your question now. Can u restate what your issue is? – Raghul Raj Jun 11 '20 at 18:12
0

df['A']=df.apply(lambda x: x['B'] if x['A']==np.NaN else x['A'],axis=1)