Reputation: 43
How to convert string to float? Here is my code, I tried using dtype and astype method:
for f in files:
data = pd.read_csv(os.path.join(path, f), sep=";", dtype={"Unnamed: 5":float})
data=data.drop(data.index[:4])
df = df.append(data)
for x in df:
print(x)
if x == "Unnamed: 0":
feeName = df["Unnamed: 0"]
generalLedger = df["Unnamed: 3"]
amount = df["Unnamed: 5"].astype(np.float64)
print(feeName, generalLedger, amount)
index = 0
sumManagementFee = 0
for x in feeName:
if x == "Management Fee":
rows = float(amount.iloc[index])
sumManagementFee += rows
The error is:
File "pandas/_libs/parsers.pyx", line 756, in pandas._libs.parsers.TextReader.read
File "pandas/_libs/parsers.pyx", line 771, in pandas._libs.parsers.TextReader._read_low_memory
File "pandas/_libs/parsers.pyx", line 850, in pandas._libs.parsers.TextReader._read_rows
File "pandas/_libs/parsers.pyx", line 982, in pandas._libs.parsers.TextReader._convert_column_data
File "pandas/_libs/parsers.pyx", line 1056, in pandas._libs.parsers.TextReader._convert_tokens
ValueError: could not convert string to float: 'Amount'
Upvotes: 1
Views: 2502
Reputation: 1878
So, your error shows that there is an 'Amount'
string in the column "Unnamed: 5"
that you're trying to convert.
You can remove it manually, or you can try using pd.to_numeric
:
amount = pd.to_numeric(df["Unnamed: 5"], errors='coerce')
Instead of
amount = df["Unnamed: 5"].astype(np.float64)
Specifying argument errors='coerce'
will replace all invalid values with NaN
Upvotes: 2