Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting Float64Index in Pandas DataFrame

I have the following code to create a df by merging to dfs which in turn are grouped by column "År" (Norwegian for Year) (2011, 2012, 2013 etc.)

def create_output_from_subset(analysis_type):
    unique_customers_subset = df.groupby('År')['Kundenavn'].nunique().to_frame()
    analyses_count_subset = df.groupby('År')['Kundenavn'].count().to_frame()
    output_subset = pd.merge(unique_customers_subset, analyses_count_subset, left_index = True, right_index = True)
return output_subset

The called function returns the following:

        Customers  Analyses
År                         
2011.0         46        59
2012.0         80       156
2013.0         76       148
2014.0         69       108
2015.0         39        82
2016.0         42        90
2017.0         23        36

The Year index (År) is formatted as a Float64Index showing 1 decimal. Any ideas how I can show it as an int (no decimals)?

like image 574
abergem Avatar asked Mar 08 '23 02:03

abergem


2 Answers

You can use index.astype:

df.index = df.index.astype(int)

But if some NaN values in index is not possible.

Need replace them by some int and then convert:

df = pd.DataFrame({'a':[1,2,3]}, index=[2011,2012,np.nan])
print (df)
         a
 2011.0  1
 2012.0  2
NaN      3

df.index = df.index.fillna(1970).astype(int)
print (df)
      a
2011  1
2012  2
1970  3

Or remove rows with NaNs first:

df = df[df.index.notnull()]
df.index = df.index.astype(int)
print (df)
      a
2011  1
2012  2
like image 102
jezrael Avatar answered Mar 15 '23 15:03

jezrael


You can try following code :

df.index = df.index.map(lambda x : int(x))
like image 34
Spandan Brahmbhatt Avatar answered Mar 15 '23 16:03

Spandan Brahmbhatt