1

I've got an excel file and I created lists from its columns. The problem is the rows of the columns is not equal. Therefore, I have multiple 'nan' values at ends of the lists. I tried to delete them with dropna() method but there are still the 'nan' values. Here is my code:

import pandas as pd

excel_name = r'file_name.xlsx'
df = pd.read_excel(excel_name, engine='openpyxl')
df.dropna()

clomun_1 = list(df['clomun1'])
clomun_2 = list(df['clomun2'])
clomun_3 = list(df['clomun3'])
print(clomun_1)
print(clomun_2)
print(clomun_3)

output:

clomun_1 = ['value1', 'value2', 'value3', 'value4', 'nan', 'nan', 'nan', 'nan']
clomun_2 = ['value1', 'value2', 'value3', 'value4', 'value5', 'value6', 'nan', 'nan']
clomun_3 = ['value1', 'value2', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan']

I want to keep only values. I must delete "nan" elements.

4
  • Does this answer your question? How to convert 'NaN' strings in a pandas Series to null values for dropna? Commented Jun 2, 2021 at 19:13
  • This was already answered on here: Remove Nan Commented Jun 2, 2021 at 19:15
  • I think you're reading literal "nan" strings from the spreadsheet. A numerical nan wouldn't have quotes around them. That's probably why dropna didn't drop them. Commented Jun 2, 2021 at 19:17
  • I think so. But if dropna is not working then what does? Commented Jun 2, 2021 at 19:39

2 Answers 2

3

Try this:

df = pd.read_excel(excel_name, engine='openpyxl', na_values=['nan']) #add na_values

clomun_1 = df['clomun1'].dropna().tolist()

print(clomun_1)

['value1', 'value2', 'value3', 'value4']
Sign up to request clarification or add additional context in comments.

2 Comments

returns : [True, True, True, True]
That's actually works. Thank you. You're the man.
0

You can use a lambda function to achieve this.

clomun_1_new= [x for x in clomun_1 if x!='nan']

repeat the same for other two lists.

2 Comments

Not working. 'nan ' values stille there after print(clomun_1_new)
It is working for me. Try changing the line to: clomun_1_new= [x for x in clomun_1 if str(x) != 'nan']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.