Remove Index, column name and "dtype" from print output in python (pandas dataframe)

Question:

I’m working with a dataset in python using pandas
When i perform a task and print, the output comes with some unneccesary lines like

  1. index of the row
  2. name of the column
  3. "dtype":object

I don’t want these there. for example;

I have this code to extract the country with highest cases

tmax= df_covid["totcases"].max()
tmin = df_covid["totcases"].min()
dfMax=df_covid.loc[df_covid['totcases'] == tmax, 'Country/Region']
dfMin=df_covid.loc[df_covid['totcases'] == tmin, 'Country/Region']

print(f"The country with the highest number of total cases is: {dfMax} with {tmax} total cases")

The output :

The country with the highest number of total cases is: 0    USA
Name: Country/Region, dtype: object with 5032179 total cases

My Desired Output

The country with the highest number of total cases is: USA with 5032179 total cases

Thanks

Asked By: highclef

||

Answers:

tmax= df_covid["totcases"].max()
tmin = df_covid["totcases"].min()
dfMax=df_covid.loc[df_covid['totcases'] == tmax, 'Country/Region']
dfMin=df_covid.loc[df_covid['totcases'] == tmin, 'Country/Region']

print(f"The country with the highest number of total cases is: {dfMax.iloc[0].values} with {tmax} total cases")
Answered By: Pingu

df_covid.loc in your case (when specifying boolean array for row label and single label for column) will return pd.Series object, so you would need to access the result value directly through values attribute:

tmax = df_covid["totcases"].max()
tmin = df_covid["totcases"].min()
dfMax = df_covid.loc[df_covid['totcases'] == tmax, 'Country/Region'].values[0]
dfMin = df_covid.loc[df_covid['totcases'] == tmin, 'Country/Region'].values[0]

print(f"The country with the highest number of total cases is: {dfMax} with {tmax} total cases")
Answered By: RomanPerekhrest
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.