Replace all cells with "-1" in DataFrame

Question:

I have a dataframe like so:

               RANK      COUNT
'2020-01-01'    100         -1
'2020-01-02'     50         -1
'2020-01-03'     -1         75

How can I replace all occurrences of -1 with None and still preserve both the RANK and COUNT as ints?

The result should look like:

               RANK      COUNT
'2020-01-01'    100          
'2020-01-02'     50           
'2020-01-03'                75

If this isn’t possible, how can I dump the original data into a .csv file that looks like the desired result?

Asked By: Daniel

||

Answers:

using replace, replace -1 with ""

out = df.replace(-1, "")
                RANK    COUNT
'2020-01-01'    100     
'2020-01-02'    50  
'2020-01-03'              75
Answered By: Naveed
df = df.replace(-1, "")

Second Method

df['RANK'] = df['RANK'].astype(str)
df['COUNT'] = df['COUNT'].astype(str)
df = df.replace('-1', "")
df['RANK'] = df['RANK'].astype(int)
df['COUNT'] = df['COUNT'].astype(int)
Answered By: Ashutosh
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.