在熊猫数据框中将字符串转换为浮点数时遇到问题

时间:2018-10-11 00:40:01

标签: python pandas

试图用熊猫数据框制作散点图,但是“ ValueError:x和y必须具有相同的大小”不断弹出。看起来Slaughter Steers数据列是字符串而不是浮点数,因此请尝试将其转换,但ValueError:无法将字符串转换为浮点数:发生“ 1,062.6”。试图用空格仍然相同的错误替换'。

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np



#Read in Data set date as index
cattle_price = pd.read_csv('C:/Users/SkyLH/Documents/CattleForcast Model/Slaughter Cattle Monthly Data.csv', index_col = 'DATE')
cattle_slaughter = pd.read_csv('C:/Users/SkyLH/Documents/Cattle Forcast Model/SlaughterCountsFull - Sheet1.csv', index_col = 'Date')
cattle_price.index = pd.to_datetime(cattle_price.index)
cattle_price.index.names = ['Date',]


cattle_slaughter.replace("'"," ")
cattle_slaughter.astype(float)

cattle_df = cattle_price.join(cattle_slaughter, how = 'inner')

print(cattle_df)
plt.scatter(cattle_df, y = 'Price')
plt.show()

                Price Slaughter Steers
Date                                  
1955-01-01  34.899999            983.8
1955-02-01  35.999998            847.9
1955-03-01  34.600001          1,062.6
1955-04-01  35.800002          1,000.9
1955-05-01  33.100002          1,090.1

1 个答案:

答案 0 :(得分:0)

相信逗号(千位分隔符)会阻止转换。这个问题有可能对您有帮助的解决方案:

How do I use Python to convert a string to a number if it has commas in it as thousands separators?