Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

pandas replace values with only whitespace to null

df = pd.DataFrame([
    [-0.532681, 'foo', 0],
    [1.490752, 'bar', 1],
    [-1.387326, 'foo', 2],
    [0.814772, 'baz', ' '],     
    [-0.222552, '   ', 4],
    [-1.176781,  'qux', '  '],         
], columns='A B C'.split(), index=pd.date_range('2000-01-01','2000-01-06'))

# replace field that's entirely space (or empty) with NaN
print(df.replace(r'^s*$', np.nan, regex=True))
# Produces:
#                    A    B   C
# 2000-01-01 -0.532681  foo   0
# 2000-01-02  1.490752  bar   1
# 2000-01-03 -1.387326  foo   2
# 2000-01-04  0.814772  baz NaN
# 2000-01-05 -0.222552  NaN   4
# 2000-01-06 -1.176781  qux NaN

# NOTE: if you don't want an element containing space in the middle to be replaced with NaN 
# use df.replace(r'^s+$', np.nan, regex=True)
Comment

PREVIOUS NEXT
Code Example
Python :: python accept user input 
Python :: function to convert minutes to hours and minutes python 
Python :: discord python command alias 
Python :: dataframe index rename 
Python :: python extract mails from string 
Python :: dataframe groupby to dictionary 
Python :: how to write a font in pygame 
Python :: variance calculation python manually 
Python :: python check if character before character in alphabet 
Python :: print 1 thing repeatedly in 1 line python 
Python :: how to set the size of a gui in python 
Python :: replacing values in pandas dataframe 
Python :: python open dicom 
Python :: ValueError: logits and labels must have the same shape ((None, 1) vs (None, 2)) 
Python :: numpy.datetime64 to datetime 
Python :: Make solutions faster in python 
Python :: remove all rows where one ccolumns egale to nan 
Python :: delete a record by id in flask sqlalchemy 
Python :: normalise min max all columns pandas 
Python :: change python 3.5 to 3.6 ubuntu 
Python :: polynomial features random forest classifier 
Python :: how to send a message from google form to a python 
Python :: sqlalchemy delete by id 
Python :: python import specific excel sheet 
Python :: spike python 
Python :: python remove directory not empty 
Python :: python rock paper scissor 
Python :: how to create list from a to z in python 
Python :: matplotlib add legend axis x 
Python :: How to make an simple python client 
ADD CONTENT
Topic
Content
Source link
Name
4+6 =