I want to delete a line that the column[3] is not 0 in python.
#prepare
from numpy import nan as NA
from pandas import Series,DataFrame
data=DataFrame([[1.,6.5,3.,0],[1.,NA,NA,0.],[NA,NA,NA,1],[NA,6.5,3.,7.]])
data
0 1 2 3
0 1.0 6.5 3.0 0.0
1 1.0 NaN NaN 0.0
2 NaN NaN NaN 1.0
3 NaN 6.5 3.0 7.0
I performed the following code,but it didn't work well.
Third=data[3]
for i in range(len(data.index)):
if not Third[i] is 0:
drop_idx=[i]
data.drop(drop_idx,axis=0)
Result
0 1 2 3
1 1.0 NaN NaN 0.0
2 NaN NaN NaN 1.0
3 NaN 6.5 3.0 7.0
0 1 2 3
0 1.0 6.5 3.0 0.0
2 NaN NaN NaN 1.0
3 NaN 6.5 3.0 7.0
0 1 2 3
0 1.0 6.5 3.0 0.0
1 1.0 NaN NaN 0.0
3 NaN 6.5 3.0 7.0
0 1 2 3
0 1.0 6.5 3.0 0.0
1 1.0 NaN NaN 0.0
2 NaN NaN NaN 1.0
I would like to know how to get the following result.Could you tell me where wrong?
0 1 2 3
0 1.0 6.5 3.0 0.0
1 1.0 NaN NaN 0.0
This will do the job:
import pandas as pd
data=pd.DataFrame([[1.,6.5,3.,0],[1.,None,None,0.],[None,None,None,1],[None,6.5,3.,7.]])
data=data[data[3]==0]
Then data
is
0 1 2 3
0 1.0 6.5 3.0 0.0
1 1.0 NaN NaN 0.0
You could also do that inplace as follows:
import pandas as pd
data=pd.DataFrame([[1.,6.5,3.,0],[1.,None,None,0.],[None,None,None,1],[None,6.5,3.,7.]])
data.drop(data[data[3]!=0].index,inplace=True)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.