pandas 删除某一行/列,采用drop函数:
DataFrame.drop(labels=None,axis=0, index=None, columns=None, inplace=False)
参数说明:
labels:要删除的列或者行,如果要删除多个,传入列表
axis :轴的方向,0为行,1为列,默认为0
index :指定要删除的行
columns :指定要删除的列
inplace=False,删除操作不改变原数据,而是返回一个执行删除操作后的新dataframe(默认);
inplace=True,在原数据上进行删除操作。
实例:
import pandas as pd
data = {'number':[1,2,3,4,5,6],'character':['a','b','c','d','e','f']}
df = pd.DataFrame(data)
df_1 = df.drop(index = [0,1]) # 删除指定行
df_2 = df.drop(columns = ['character']) # 删除指定列
print('df:\n',df,'\n','df_1:\n',df_1,'\n','df_2:\n',df_2)
输出结果:
df:
number character
0 1 a
1 2 b
2 3 c
3 4 d
4 5 e
5 6 f
df_1:
number character
2 3 c
3 4 d
4 5 e
5 6 f
df_2:
number
0 1
1 2
2 3
3 4
4 5
5 6
numpy 删除某一行/列,采用delete函数:
numpy.delete(arr, obj, axis=None)
参数说明:
arr:输入array
obj:整数 or 整数列表,表示哪个子数组要被移除
axis:删除子数组的轴
axis = None:表示把数组按一维数组平铺在进行索引删除
实例:
import numpy as np
x = np.array(np.arange(0, 16).reshape(4, 4))
print(" x:\n",x)
y = np.delete(x, 1, axis=1) # 删除指定一列
print(" y:\n",y)
z = np.delete(x, 0, axis=1) #删除指定一行
print(" z:\n",z)
m = np.delete(x, [1,2], axis=1) # 删除指定多列
print(" m:\n",m)
输出结果:
x:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
y:
[[ 0 2 3]
[ 4 6 7]
[ 8 10 11]
[12 14 15]]
z:
[[ 1 2 3]
[ 5 6 7]
[ 9 10 11]
[13 14 15]]
m:
[[ 0 3]
[ 4 7]
[ 8 11]
[12 15]]
Python中内置的Del函数,可以删除单个元素,或者指定范围内的值和整个对象
示例:
list_1 = [1,2,3,4,5,6,7]
print(list_1)
del list_1[2:5]
print(list_1)
输出结果:
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 6, 7]