Page 224 - AI Ver 3.0 Class 11
P. 224

• •  head(n): This method returns the first n rows of the DataFrame. If n is not specified, it defaults to 5.
                      print(df.head(2))
                   Output:

                           Product   Price    Stock   Rating

                      0      Laptop    1000       50      4.5
                      1    Tablet     500      150      4.0
               • •  tail(n): This method returns the last n rows of the DataFrame. If n is not specified, it defaults to 5.
                      print(df.tail(2))
                  Output:

                            Product  Price  Stock  Rating
                      2  Smartphone    800    200     4.7
                      3     Monitor    300    100     4.3

              Importing a CSV file into a DataFrame
              This function is versatile and handles various configurations of CSV files, making it straightforward to load data for
              analysis or manipulation.

              You can import a CSV file into a pandas DataFrame using the read_csv() function. The syntax of the read_csv()
              function is:


                                                  pd.read_csv("filename.csv")

              where, filename.csv is the name of the file with .csv extension that you want to import.

              The pd.read_csv() function in pandas is quite versatile and allows you to specify various parameters to customise
              how the CSV file is read. Some commonly used parameters are as follows:
               • •  filepath: The path to the CSV file.
               • •    sep: The delimiter to use for separating columns. These delimiters can be a comma, semicolon, tab, or any other
                  character. The default value for ‘sep’ is a comma.
               • •    header: It specifies which row to use as column names. ‘header=0’ means the column names are taken from the
                  first line of the file. By default, ‘header=0’.
               • •  index_col: It specifies which column to use as the row labels.
               • •  dtype: A dictionary where keys are column names and values are data types.

               • •  encoding: It specifies the encoding to use for reading the file.
               • •  compression: It specifies the compression mode for reading compressed files.

                Program 56: To import a CSV file into DataFrame

                   # importing pandas library
                   import pandas as pd

                   # making data frame
                   #specify path of file in case file is in a different folder

                   df = pd.read_csv("Customer.csv",sep=',', header=0)
                   print(df)


                    222     Touchpad Artificial Intelligence (Ver. 3.0)-XI
   219   220   221   222   223   224   225   226   227   228   229