Home > Enterprise >  ValueError: could not convert string to float: 'Null' (Pandas)
ValueError: could not convert string to float: 'Null' (Pandas)

Time:04-18

I'm trying to write the value of a row to "Null" but it doesn't seem to work. I get the following error: ValueError: could not convert string to float: 'Null'

test.csv:

SIDE,PRICE,QTY,OPEN
BUY,0.25,0.22,True
BUY,0.26,0.23,True
BUY,0.27,0.24,True
BUY,0.28,0.25,True

Code:

import pandas as pd
import csv

test_dataframe = pd.read_csv('test.csv')

test_dataframe.at[2, 'OPEN'] = False
test_dataframe.at[2, 'QTY'] = "Null"

test_dataframe.to_csv("test.csv", index=False)

How can I write "Null" to a row because that's what I want?

CodePudding user response:

Don't use a string but a float:

df.at[2, 'QTY'] = float('nan')

Or, using numpy:

df.at[2, 'QTY'] = np.nan

While you could use "Null" (and recent versions of pandas will allow df.at[2, 'QTY'] = "Null"), this would convert your Series to object type and you would lose benefit of vectorization. Ask yourself the question "what would be the benefit of having "Null"?".

If your goal is just to modify a CSV, then use strings, not floats, when importing the data.

CodePudding user response:

Instead of using:

test_dataframe.at[2, 'QTY'] = "Null"

You can use this instead to change the value of any row within any column to "Null"(i.e. In this case I have implemented it to the third row of the third column.

test_dataframe.loc[2, "QTY"] = 'Null'

This code worked well in my case, please do comment if you are facing with any issue:

enter image description here

  • Related