我正在尝试从csv读取数据并计算新值。熊猫将数据解释为字符串,因此,我无法对值进行数学运算。尝试将值转换为浮点数也会失败。将字符串df
转换为floats
的正确方法是什么?
import pandas as pd
df = pd.read_csv('data.csv', names=['Open','High','Low','Close'])
#TypeError: unsupported operand type(s) for -: 'str' and 'str'
df['HL_PCT'] = (df['High']-df['Low'])/df['Close']
#ValueError: could not convert string to float: 'Low'
df['HL_PCT'] = (df['High'].astype(float)-df['Low'].astype(float))/df['Close'].astype(float)
print(df.head())
# head.csv
# Open,High,Low,Close
# 100.1,110.1,90.1,101.1
# 100.2,110.2,90.2,101.2
# 100.3,110.3,90.3,101.3
# 100.4,110.4,90.4,101.4
答案 0 :(得分:0)
问题是由标题引起的。应该跳过这样:
df = pd.read_csv('data.csv', names=['Open','High','Low','Close'], skiprows=[0])