首页 > 解决方案 > Pandas 不会从数据框中删除列

问题描述

我试图删除列:

prediction.drop('1',axis=1)

但是在将数据框保存到 csv 之后:

prediction.to_csv(path_or_buf='./path/file.csv')

我打开文件并看到以下内容:

,TARGET,1
0,1.0,0.0
1,1.0,0.0
2,1.0,0.0

pandas 还认为第一列根本不存在(名为 ' ' 的列)。pandas 对任何数据框都执行此操作。如果我将尝试:

prediction.drop('',axis=1)

它会抛出:

KeyError: "[''] not found in axis"

这是生成数据的代码:

from keras.models import load_model
import pandas as pd
import numpy as np
model = load_model(filepath='./DRISK/model_mlp_a2.h5')
TEST = pd.DataFrame.from_csv('./DRISK/application_test.csv')
expanded = np.zeros((48744,4))
def encode_array(features):
    features = features.fillna(0)
    features = pd.get_dummies(features)
    features = np.array(features)
    features = np.append(features,expanded)
    features = np.reshape(features,(48744,251))
    return features
TEST_X = encode_array(TEST)
prediction = model.predict(x=TEST_X,verbose=1)
prediction = pd.DataFrame(prediction,columns=['TARGET','1'])
prediction.drop('',axis=1)
prediction.to_csv(path_or_buf='./DRISK/predictions.csv')

我在谷歌上广泛搜索了这个问题,但无济于事。PS 此外,它忽略了所有其他数据框中的第一列。

标签: pythonpandas

解决方案


推荐阅读