5

I have a DataFrame with two columns X and Y:

   X      Y
0  0  111.0
1  3    NaN
2  1    NaN
3  1  112.0
4  2  113.0
5  2    NaN
6  3  114.0
7  3  115.0
8  1    NaN
9  2  116.0

I want to copy in Y only the values of X that correspond to the rows where a NaN is. The expected result should look like this

   X    Y
0  0  111
1  3    3
2  1    1
3  1  112
4  2  113
5  2    2
6  3  114
7  3  115
8  1    1
9  2  116

Is there any way to achieve this?

Yiyi
  • 108
  • 1
  • 1
  • 7
  • 3
    `df["Y"] = df["Y"].fillna(df["X"])` – Rakesh Jun 26 '18 at 09:44
  • Thanks. I am so new working with pandas, so i did´t know about the `fillna()` option. So that also explain why my question was already posted but with other tittle – Yiyi Jun 26 '18 at 11:44

4 Answers4

7

You can simply use the fillna() function available in pandas to solve this very efficiently.

Below code explains how to it in Python.

df = pd.DataFrame()

df['X'] = [0, 3, 1, 1, 2, 2, 3, 3, 1, 2]
df['Y'] = [111.0, np.nan, np.nan, 112, 113, np.nan, 114, 115, np.nan, 116]

df['Y'] = df['Y'].fillna(df['X'])

print(df)
Sreeram TP
  • 11,346
  • 7
  • 54
  • 108
1

Use df["Y"].fillna(df["X"])

Ex:

import pandas as pd
import numpy as np
df = pd.DataFrame({"X": [3, 4, 5, 6], "Y": [10, np.nan, 7, np.nan]})
df["Y"] = df["Y"].fillna(df["X"])
print(df)

Output:

   X     Y
0  3  10.0
1  4   4.0
2  5   7.0
3  6   6.0
Rakesh
  • 81,458
  • 17
  • 76
  • 113
1

Here one liner:

df.loc[df['Y'].isnull(), 'Y'] = df['X']
Allan J
  • 31
  • 2
0

Another way:

df['Y'] = [row[-2] if row[-1]=='Nan' else row[-1] for row in df.itertuples()]
print(df)

Output:

   X    Y
0  0  111
1  3    3
2  1    1
3  1  112
4  2  113
5  2    2
6  3  114
7  3  115
8  1    1
9  2  116
U13-Forward
  • 69,221
  • 14
  • 89
  • 114