TheDaJon
TheDaJon

Reputation: 565

Python Pandas - Merge two columns in a dataframe

I have a pandas df that looks like this:

     TTL1    TTL2
0    val1    
1    val2   
2    val3
3             val4
4    val5    
5    val6   
6    val7
7             val8

and I want to make it like so:

     TTL1
0    val1    
1    val2   
2    val3
3    val4
4    val5    
5    val6   
6    val7
7    val8

any ideas please on how I can get this done?

Upvotes: 1

Views: 1257

Answers (4)

Ted Petrou
Ted Petrou

Reputation: 61947

There is a bit ambiguity in the problem but the pandas method stack is used to put all values into a single column.

df.stack()

Output

0  TTL1    val1
1  TTL1    val2
2  TTL1    val3
3  TTL2    val4
4  TTL1    val5
5  TTL1    val6
6  TTL1    val7
7  TTL2    val8
dtype: object

Upvotes: 0

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210832

yet another solution (assuming OP has NaN's in the TTL1 column):

In [127]: df.TTL1.fillna(df.TTL2)
Out[127]:
0    val1
1    val2
2    val3
3    val4
4    val5
5    val6
6    val7
7    val8
Name: TTL1, dtype: object

Upvotes: 1

piRSquared
piRSquared

Reputation: 294218

set_up

df = pd.DataFrame([
        ['val1', np.nan],
        ['val2', np.nan],
        ['val3', np.nan],
        [np.nan, 'val4'],
        ['val5', np.nan],
        ['val6', np.nan],
        ['val7', np.nan],
        [np.nan, 'val8']
    ], columns=['TTL1', 'TTL2'])

simplest answer is to use combine_first

df.TTL1.combine_first(df.TTL2).to_frame()

   TTL1
0  val1
1  val2
2  val3
3  val4
4  val5
5  val6
6  val7
7  val8

If those blanks are actually '' then do this first

df.replace('', np.nan, inplace=True)

Upvotes: 2

Zero
Zero

Reputation: 76917

How about conditional setting?

In [260]: df.loc[df.TTL1 == '', 'TTL1'] = df.TTL2

In [261]: df
Out[261]:
   TTL1  TTL2
0  val1
1  val2
2  val3
3  val4  val4
4  val5
5  val6
6  val7
7  val8  val8

Alternatively, using np.where

In [266]: df.TTL1 = np.where(df.TTL1 == '', df.TTL2, df.TTL1)

In [267]: df
Out[267]:
   TTL1  TTL2
0  val1
1  val2
2  val3
3  val4  val4
4  val5
5  val6
6  val7
7  val8  val8

Upvotes: 3

Related Questions