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 :: drop rows with null date in pandas 
Python :: download image python from url 
Python :: amazon response 503 python 
Python :: selenium webdriver 
Python :: clear python list 
Python :: python 1 to 01 
Python :: real time crypto prices python 
Python :: docs.python.org 
Python :: Network.py socket 
Python :: python df select first x columns 
Python :: how to convert multi list to dict 
Python :: binary string to hex python 
Python :: django custom primary key field 
Python :: python sum dictionary values by key 
Python :: link python to python3 
Python :: one hot encoding numpy 
Python :: flask mail python 
Python :: python get response headers 
Python :: Python - Count the Number of Keys in a Python Dictionary 
Python :: numpy apply function to array 
Python :: list of files to zip python 
Python :: printing python dictionary values 
Python :: concat dataframe from list of dataframe 
Python :: pytest loop 
Python :: how to add subplots for histogram 
Python :: pil image to numpy 
Python :: convert pandas column type 
Python :: how to take unknown number of inputs in python 
Python :: multiple inputs in python 
Python :: how to use sum with range python 
ADD CONTENT
Topic
Content
Source link
Name
5+1 =