#! /usr/bin/env python3 # def dataframe_test ( ): import pandas as pd print ( '' ) print ( 'dataframe_test():' ) print ( ' Demonstrate the use of Dataframes in pandas.' ) # # Create a DataFrame from a dictionary. # print ( '' ) print ( ' Create a DataFrame from a dictionary.' ) print ( " moon_data = { " ) print ( " 'mass' : [ 1.482e23, 1.076e23, 8.932e23, 4.800e22, 7.342e22 ], " ) print ( " 'radius' : [ 2.634e6, None, 1.822e6, None, 1.737e6 ], " ) print ( " 'parent' : [ 'Jupiter', 'Jupiter', 'Jupiter', 'Jupiter', 'Earth' ] }" ) print ( " moon_index = [ 'Ganymede', 'Callisto', 'Io', 'Europa', 'Moon' ]" ) print ( " moon_df = pd.DataFrame ( moon_data, index = moon_index )" ) moon_data = { \ 'mass' : [ 1.482e23, 1.076e23, 8.932e23, 4.800e22, 7.342e22 ], \ 'radius' : [ 2.634e6, None, 1.822e6, None, 1.737e6 ], \ 'parent' : [ 'Jupiter', 'Jupiter', 'Jupiter', 'Jupiter', 'Earth' ] } moon_index = [ 'Ganymede', 'Callisto', 'Io', 'Europa', 'Moon' ] moon_df = pd.DataFrame ( moon_data, index = moon_index ) input ( 'RETURN' ) # # Print the information. # print ( '' ) print ( ' print ( moon_df ):' ) print ( moon_df ) input ( 'RETURN' ) # # Use loc() to see a value. # print ( '' ) print ( ' Print a row using loc[]' ) print ( ' print ( moon_df.loc["Europa"] )' ) print ( moon_df.loc['Europa'] ) input ( 'RETURN' ) print ( '' ) print ( ' Print a column using loc[]' ) print ( ' print ( moon_df.loc[:,"mass"] )' ) print ( moon_df.loc[:,'mass'] ) input ( 'RETURN' ) print ( '' ) print ( ' Print an entry (a cell) using loc[]' ) print ( ' print ( moon_df.loc["Europa","mass" )' ) print ( moon_df.loc['Europa','mass'] ) input ( 'RETURN' ) # # Use loc() to change a value. # print ( '' ) print ( ' Change an entry using loc[]' ) print ( ' print ( moon_df.loc["Callisto","radius" )' ) print ( moon_df.loc['Callisto','radius'] ) input ( "RETURN" ) moon_df.loc['Callisto','radius'] = 2410300 print ( '' ) print ( ' moon_df.loc["Callisto","radius"] = 2410300' ) print ( moon_df ) input ( 'RETURN' ) # # Select a portion of the DataFrame # print ( '' ) print ( ' Select a portion of the DataFrame using loc[]:' ) print ( '' ) print ( ' moon_df.loc[:,["mass","radius"]]' ) print ( moon_df.loc[:,['mass','radius']] ) print ( '' ) print ( ' moon_df.loc[["Moon","Europa"],"parent"]' ) print ( moon_df.loc[['Moon','Europa'],'parent'] ) print ( '' ) print ( ' moon_df.loc[moon_df.parent=="Jupiter","radius"]' ) print ( moon_df.loc[moon_df.parent=='Jupiter','radius'] ) input ( 'RETURN' ) # # Use iloc() to see a value using numeric index. # print ( '' ) print ( ' Print a row using iloc[] and numeric index' ) print ( ' print ( moon_df.iloc[3] )' ) print ( moon_df.iloc[3] ) print ( '' ) print ( ' Print a column using iloc[]' ) print ( ' print ( moon_df.iloc[:,0] )' ) print ( moon_df.iloc[:,0] ) print ( '' ) print ( ' Print an entry (a cell) using iloc[]' ) print ( ' print ( moon_df.iloc[3,0] )' ) print ( moon_df.iloc[3,0] ) input ( 'RETURN' ) return if ( __name__ == "__main__" ): dataframe_test ( )