0

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?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Daniel
  • 3,228
  • 1
  • 7
  • 23
  • 2
    This isn't possible as integer, but you can as string/object – mozway Nov 16 '22 at 20:15
  • If for some reason you need a numeric dtype and want to avoid object, you could use Nan and convert them to float. – Ignatius Reilly Nov 16 '22 at 20:31
  • Does this answer your question? [NumPy or Pandas: Keeping array type as integer while having a NaN value](/q/11548005/4518341). Note that `df.to_csv()` represents NaN as `''` by default. – wjandrea Nov 16 '22 at 20:38

2 Answers2

1

using replace, replace -1 with ""

out = df.replace(-1, "")
                RANK    COUNT
'2020-01-01'    100     
'2020-01-02'    50  
'2020-01-03'              75
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Naveed
  • 11,495
  • 2
  • 14
  • 21
  • 1
    This doesn't keep the column dtypes as int. Although, OP's accepted this answer, so maybe they're OK with that? I'm not sure. – wjandrea Nov 16 '22 at 20:44
-2
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)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Ashutosh
  • 1
  • 2