'How do you input NaN valiues in 1st row 1st column?
import pandas as pd
data=['a',2,],['b',4,1],['c',6,],['d',4.4,]
df = pd.DataFrame(data, columns = ['Name', 'Age','number'])
df
Name Age number
0 a 2.0 NaN
1 b 4.0 1.0
2 c 6.0 NaN
3 d 4.4 NaN
I wanted to replace "a" with NaN values (1st row 1st column)
This error shows up
data=[,2,],['b',4,1],['c',6,],['d',4.4,]
^
SyntaxError: invalid syntax
I have tried this instead
data=['',2,],['b',4,1],['c',6,],['d',4.4,]
df = pd.DataFrame(data, columns = ['Name', 'Age','number'])
df
Name Age number
0 2.0 NaN
1 b 4.0 1.0
2 c 6.0 NaN
3 d 4.4 NaN
I then checked for missing values and obviously it is not picking up the empty values in , row1,column 1
na= [features for features in df.columns if df[features].isnull().sum()>0]
na
['number']
Any suggestions on how to navigate through this issue. Thank You
Solution 1:[1]
Pandas is built in numpy, so simply use np.nan:
import numpy as np
data=[np.nan,2,],['b',4,1],['c',6,],['d',4.4,]
df = pd.DataFrame(data, columns = ['Name', 'Age','number'])
print (df)
Ouput:
Name Age number
0 NaN 2.0 NaN
1 b 4.0 1.0
2 c 6.0 NaN
3 d 4.4 NaN
Solution 2:[2]
You can simply use:
float('nan')
Solution 3:[3]
Pandas docs recommend .iat for getting / setting individual values on dataframes. Indexed by row / column pair starting from 0.
So in your case, to set column 'Name' / row 0 to numpy's nan type (imported as np below) this would be:
df.iat[0,0] = np.nan
Solution 4:[4]
you can use math module on NaN value
import pandas as pd
import math
data=[math.nan,2,],['b',4,1],['c',6,],['d',4.4,]
df = pd.DataFrame(data, columns = ['Name', 'Age','number'])
df
output
Name Age number
0 NaN 2.0 NaN
1 b 4.0 1.0
2 c 6.0 NaN
3 d 4.4 NaN
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tamil Selvan |
| Solution 2 | Mazhar |
| Solution 3 | ivanp |
| Solution 4 | Tamil Selvan |
