我正在使用Pandas读取CSV文件,该文件包含必须转换为浮点数的几列:
df = pd.read_csv(r'dataset.csv', low_memory=False, sep = ',')
df.head(2)
Coal Flow 01 Air Flow 01 Outlet Temp 01 Inlet Temp 01 Bowl DP 01 Current 01 Vibration 01
0 51.454407 101.432340 64.917089 234.2488932 2.470623 96.727352 1.874374
1 51.625368 100.953089 64.726890 233.2340394 2.495698 96.309512 1.996391
接下来,在名为
features
的变量中指定需要转换为浮点数的列: features = ['Coal Flow 01', 'Air Flow 01', 'Outlet Temp 01', 'Inlet Temp 01',
'Bowl DP 01', 'Current 01', 'Vibration 01']
然后,我需要将列的值转换为float,但是出现错误。
features = np.stack([df[col].values for col in features], 1)
features = torch.tensor(features, dtype=torch.float)
features[:5]
熊猫显示给我的错误是:
KeyError:“ [[([51.45440668,101.4323397,64.91708906,'234.2488932',\ n 2.470623484,96.72735193,1.87437372],\ n dtype ='object')]都不在[列]中”
最佳答案
为什么不只使用astype
:
df = pd.read_csv(r'dataset.csv', low_memory=False, sep = ',')
df[features] = df[features].apply(lambda x: x.apply(lambda x: x[0]).astype(float))
关于python - 无法将Pandas Dataframe列转换为float,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59350190/