Home > Enterprise >  dropping rows from dataframe when column contains a decimal value
dropping rows from dataframe when column contains a decimal value

Time:05-30

I have a dataframe with the column SimTime, which has values like

SimTime
0
2
4
4.4
6
6.4
8

I only want to keep values which are integers and I am using the following snippet, however, I'm unable to see any changes in the dataframe.

df=df.drop(df.index[(df['SimTime']%1).astype(int)!=0])

CodePudding user response:

Try this

df = pd.DataFrame({'SimTime': [0, 2, 4, 4.4, 6, 6.4, 8]})
# filter rows where rounding doesn't matter, i.e. ints
df[df.SimTime==df.SimTime.round()].astype(int)

enter image description here

CodePudding user response:

Use:

df1 = df[df.SimTime==df.SimTime.astype(int)]

Your solution:

df1 = df[(df['SimTime']%1).eq(0)]

CodePudding user response:

Your code almost works, you just have the astype method in the wrong place. It should be:

df = df.drop(df.index[df['SimTime'] % 1 != 0]).astype(int)

But in case there is more than one column in the dataframe, you may want to convert just the one column to integer:

df.drop(df.index[df['SimTime'] % 1 != 0], inplace=True)
df['SimTime'] = df['SimTime'].astype(int)
  • Related