How to print excel column non null value with python?

Question:

I have the following excel sheet:enter image description here

and want to print column 1 value if the column 2 value is not null. The output should be [1,3].

This the script created by me, but it doesn’t work:

import xlrd
import pandas as pd

filename='test.xlsx'
dataframe = pd.read_excel(filename)
frame = dataframe.loc[dataframe["col2"] !=" "]
df =  frame.iloc[:, 0]

ndarray = df.to_numpy()
print(ndarray)
Asked By: liuxu

||

Answers:

You can first filter down to nona rows and then show the values of the column you want to show:

dataframe[df['col2'].notna()]['col1'].values
Answered By: Andreas

If you print the dataframe, you will see that the empty cells are NaN:

      Col1 Col2
 0     1    a
 1     2  NaN
 2     3    b
 3     4  NaN

So, you need to use the notna() method to filter

Here is your fixed code:

import xlrd
import pandas as pd

filename='test.xlsx'
dataframe = pd.read_excel(filename)
frame = dataframe.loc[dataframe["col2"].notna()]
df =  frame.iloc[:, 0]

ndarray = df.to_numpy()
print(ndarray)
Answered By: Roniel López
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.