[英]how to drop a range of columns in pandas?
我有一个非常大的 dataframe,有 108 列和 8000 行,我想删除一些列。 它没有特定的列名,它只有索引作为列名。
我要删除的列是从 74 到 104。
我试过了:
df.drop(['74', '104'], axis = 1, inplace = True)
但它说:
['74' '104'] not found in axis
其中 74 和 104 是我要删除的列索引。
我该如何解决这个问题?
先感谢您
当您使用索引引用列时,您应该将它们视为整数。
df.drop([74, 104], axis=1, inplace=True)
例子:
>>> df = pd.DataFrame([[1,2,3],[4,5,6]])
>>> df
0 1 2
0 1 2 3
1 4 5 6
>>> df.drop([1], axis=1)
0 2
0 1 3
1 4 6
按索引删除列,例如:
data= {1:[1,19,20,21,25,29,30,31,30,29,31],
2: [2,10,20,20,20,10,10,20,20,10,10],
3: [3,10,20,20,20,10,10,20,20,10,10],
4: [4,10,20,20,20,10,10,20,20,10,10]}
index= pd.date_range('12/1/2019', periods=11)
df=pd.DataFrame(data, index=index)
去向
会给你
1 2 3 4
2019-12-01 1 2 3 4
2019-12-02 19 10 10 10
2019-12-03 20 20 20 20
2019-12-04 21 20 20 20
2019-12-05 25 20 20 20
2019-12-06 29 10 10 10
2019-12-07 30 10 10 10
2019-12-08 31 20 20 20
2019-12-09 30 20 20 20
2019-12-10 29 10 10 10
2019-12-11 31 10 10 10
然后(假设您希望删除第 0、1、2 列的索引):
df.drop(df.columns[[0,1,2]], axis=1, inplace=True)
期望的结果:
4
2019-12-01 4
2019-12-02 10
2019-12-03 20
2019-12-04 20
2019-12-05 20
2019-12-06 10
2019-12-07 10
2019-12-08 20
2019-12-09 20
2019-12-10 10
2019-12-11 10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.