列可以通过drop或del删除。
#+begin_src ipython :session alinbx :results output
import pandas as pd
import numpy as np
df = pd.DataFrame(np.arange(12).reshape(3, 4),
columns=['A', 'B', 'C', 'D'])
print(df, '\n'+'--'*50)
# Drop columns
print(df.drop(['B', 'C'], axis=1), '\n'+'--'*50)
del df['A']
# Drop a row by index
print(df.drop([0, 1]), '\n'+'--'*50)
print(df.drop([0, 1], axis=0))
#+end_src
#+RESULTS:
#+begin_example
A B C D
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
----------------------------------------------------------------------------------------------------
A D
0 0 3
1 4 7
2 8 11
----------------------------------------------------------------------------------------------------
B C D
2 9 10 11
----------------------------------------------------------------------------------------------------
B C D
2 9 10 11
#+end_example当尝试用del删除rwo时,它会报告错误。
#+begin_src ipython :session alinbx :results output
del df.iloc[0, :]
#+end_src
AttributeErrorTraceback (most recent call last)
<ipython-input-20-4fdbabf9cb4f> in <module>
----> 1 del df.iloc[0, :]
AttributeError: __delitem__如何删除带有“del`”的行
发布于 2019-10-11 13:14:54
不能删除带有del的行,因为.loc或.iloc返回的行是DataFrame的副本,因此删除它们对实际数据没有任何影响。
观察:
>>> df['A'] is df['A']
True
>>> df.loc[0] is df.loc[0]
False
>>> df.iloc[0, :] is df.loc[0, :]
Falsedel df['A']之所以工作,是因为它使用__getitem__检索实际对象,因此,通过移除键'A',它还将删除框架的相关列数据。
若要删除行,则需要使用df.drop(index=0)或df.drop([0], axis=0)。若要删除多行,假定索引是df.drop(index=range(...))的,则int也可以工作。
https://stackoverflow.com/questions/58341588
复制相似问题