1

I have the below dataframe wherein I am trying to remove the first column which is the default column assigned in pandas dataframe/series. How do I get rid of that?

Actual Result

Actual result should be without the first column which has the "0". I have tried using reset index with drop but nothing works.

Here is my code which sends a mail with the dataframe output.

def send_email(index):
    fromaddr = ""
    toaddr = ""
    msg = MIMEMultipart()
    msg['From'] = fromaddr
    msg['To'] = toaddr
    msg['Subject'] = "Timestamp Alarm"
    df1 = df.iloc[index,1:]
    new = df1

    body = """\
<html>
  <head></head>
  <body>
    {0}
  </body>
</html>
""".format(pd.DataFrame(new).T.to_html())
    part1 = MIMEText(body,'html')
    msg.attach(part1)
    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.starttls()
    server.login('***', '**')
    server.sendmail('','',msg.as_string())
    server.quit()
Krishnamurthy
  • 139
  • 2
  • 8

2 Answers2

1

Look at to_html documentation.

This fuction contains a.o. index parameter (default True), deciding whether to generate the index column.

Maybe you should pass it with False value.

Another option:

Print the DataFrame (and then send) as "ordinary" text.

To hide the index column, also pass index=False:

print(df.to_string(index=False))
Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41
  • Thank you. I have already figured it out though. Do you know how I can add styles to to_html? For eg. Justify columns and values? – Krishnamurthy Sep 30 '19 at 04:20
  • I found some description concerning adding classes at https://stackoverflow.com/questions/50807744/apply-css-class-to-pandas-dataframe-using-to-html – Valdi_Bo Sep 30 '19 at 05:47
  • `output1.to_csv('test.csv', index=False)` works similarly for csv as well – Vallie Jul 07 '22 at 18:58
0

See the following and relate to your problem.

Generic Solution

import pandas as pd
d = {'Field_A': 'FA', 'Field_B': 'FB', 'Field_C': 'FC'}
df = pd.DataFrame({0: d}).T
df

Output:

    Field_A Field_B Field_C
0   FA      FB      FC

Specific Solution

If all you want is the cell values for columns Field_A, Field_B, Field_C, then just call df.loc[0]. In your case, you would need to change the line where you define variable new.

new = df.loc[index]
CypherX
  • 7,019
  • 3
  • 25
  • 37