EN VI

Python - Removing first empty rows and reindexing columns in Dataframe?

2024-03-14 13:30:04
How to Python - Removing first empty rows and reindexing columns in Dataframe

I'm receiving the data in excel. Sometimes, there will be blank rows and the data starts with columns from the sheet. Sometimes, there will be no blanks. straight the data will be available without any blanks.

However I'm using the below code snippet to remove blanks and reindex the columns

df = pd.read_excel(response.content, index_col=None)
df = df.dropna(how="all").dropna(how="all", axis=1)
headers = df.iloc[0]
new_df = pd.DataFrame(df.values[1:], columns=headers)
print(new_df)

It'll work only if there are empty rows. It won't work if the data is coming without blanks. How can I handle this dynmamically?

Example Data

Sample 1

sample data 1

Result is

Output

enter image description here

Sample 2

enter image description here

Result is

enter image description here

enter image description here

Solution:

Try This,

df = pd.read_excel(response.content, header=None)
df = df.dropna(how="all").dropna(how="all", axis=1)
df = df.reset_index().drop('index', axis=1)
headers = df.iloc[0]
new_df = pd.DataFrame(df.values[1:], columns=headers)
new_df
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login