Home > Enterprise >  How to drop a row if the first column's value is empty?
How to drop a row if the first column's value is empty?

Time:09-30

I have a dataframe in which the 1st column in some of the rows are empty, and I want to drop such rows. I saw this as one way to drop row:

df = df.dropna(axis=0, subset=['1st_row']) 

I don't know the column names and I want to drop by column index (the 1st column). Is that possible?

CodePudding user response:

you could select columns (or rows) by position using iloc

for instance, the following would drop all rows where the first column is null

df = pd.DataFrame({
   'a': [pd.NA, 1, 2, 3, pd.NA, 4, 5],
   'b': list('abcdefg')
})
df2 = df[df.iloc[:,0].notnull()]

df2 outputs:

   a  b
1  1  b
2  2  c
3  3  d
5  4  f
6  5  g
  • Related