How to properly delete a column in dataframe (pandas)?
我不能用pandas从
这是我的熊猫。头()。
1 2 3 4 5 6 | age;"job";"marital";"education";"default";"balance";"housing";"loan";"contact";"day";"month";"duration";"campaign";"pdays";"previous";"poutcome";"y" 0 58;"management";"married";"tertiary";"no";2143... 1 44;"technician";"single";"secondary";"no";29;"... 2 33;"entrepreneur";"married";"secondary";"no";2... 3 47;"blue-collar";"married";"unknown";"no";1506... 4 33;"unknown";"single";"unknown";"no";1;"no";"n... |
这是我的代码:
1 2 3 4 | import pandas df = pd.read_csv('bank-full.csv') print(df.head()) df = df.drop(['day', 'poutcome'], axis=1) |
号
错误如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | Traceback (most recent call last): File"/home/administrator/PycharmProjects/BankMarketinData/main.py", line 21, in main() File"/home/administrator/PycharmProjects/BankMarketinData/main.py", line 19, in main df = df.drop(['day', 'poutcome'], axis=1) File"/home/administrator/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py", line 3697, in drop errors=errors) File"/home/administrator/anaconda3/lib/python3.6/site-packages/pandas/core/generic.py", line 3111, in drop obj = obj._drop_axis(labels, axis, level=level, errors=errors) File"/home/administrator/anaconda3/lib/python3.6/site-packages/pandas/core/generic.py", line 3143, in _drop_axis new_axis = axis.drop(labels, errors=errors) File"/home/administrator/anaconda3/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 4404, in drop '{} not found in axis'.format(labels[mask])) KeyError:"['day' 'poutcome'] not found in axis" |
所以这是一个非常简单的问题。首先,我建议您在处理
1 2 3 | import pandas as pd df = pd.read_csv('bank-full.csv') df = df.drop(['day', 'poutcome'], axis=1) |
现在你的
1 | df = df.drop(['"day"', '"poutcome"'], axis=1) |
。
我希望这对你有帮助。如果你还有什么问题,请告诉我
您可以逐个删除它们,或者使用循环删除多个列。您需要确保这些列名称是数据框中的列名称。从您的问题看来,您的列名被包装在了"中"。在读取数据帧时,请确保正确定义分隔符。当使用read_csv时,它将默认为",",但在本例中是";"。
逐一地
1 2 3 | df = pd.read_csv('bank-full.csv', sep=';') df = df.drop(['day'], axis=1) df = df.drop(['poutcome'], axis=1) |
号
回路
1 2 3 4 | df = pd.read_csv('bank-full.csv', sep=';') Drop_list = ['day','poutcome'] for column in Drop_list: df = df.drop([column], axis=1) |
我用于提问的测试:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | df = pd.DataFrame(np.random.randn(50, 4), columns=list('ABCD')) df.head(5) A B C D 0 0.860680 -0.408577 0.727530 -0.119050 1 -1.140042 0.241970 -1.509257 -0.303601 2 0.811929 0.146228 2.102941 0.772328 3 -0.590157 0.753719 0.220592 -0.563953 4 0.031505 -0.521978 0.410718 -0.325865 Drop_list = ['A','B','C'] for column in Drop_list: df = df.drop([column], axis=1) df.head(5) D 0 -0.119050 1 -0.303601 2 0.772328 3 -0.563953 4 -0.325865 |
。
1 2 3 | df = pd.read_csv('bank-full.csv', sep=';') df.columns = [col.replace('"', '') for col in df.columns] df.drop(columns=['day','poutcome'], inplace=True) |
正如您从后续评论中看到的,您的问题是在引入CSV文件时使用了错误的分隔符。然后,您需要删除列名称中的引号,以便可以删除这些列。