Page 211 - AI Ver 3.0 Class 11
P. 211

[2, 'Esha', 30],
                             [3, 'Vedant', 28]]
                     df = pd.DataFrame(data, columns=['Name', 'Age', 'City'])

                     print(df)
                     Output:
                          Name         Age     City
                     0       1       Mayur       25
                     1       2      Esha      30
                     2       3    Vedant      28
                  • •    From a Dictionary of Lists or Arrays: You can create a DataFrame from a dictionary where keys are column names
                     and values are lists or arrays containing the data for each column.

                   Program 41: To create a DataFrame using dictionary of lists or arrays

                     import pandas as pd
                     data = {'Name': ['Yash', 'Rehan', 'Neha'],
                             'Age': [25, 30, 28],
                             'City': ['Delhi', 'Mumbai', 'Bengaluru']}
                     df = pd.DataFrame(data)
                     print(df)
                 Output:
                         Name  Age       City
                     0   Yash   25      Delhi
                     1  Rehan   30     Mumbai
                     2   Neha   28  Bengaluru
                  • •    Using NumPy ndarrays: Creating DataFrames from NumPy ndarrays allows you to leverage the power of both
                     libraries for efficient data processing and analysis. NumPy provides efficient array computations, while Pandas offers
                     powerful data manipulation and analysis tools.

                   Program 42: To create a DataFrame using ndarray

                     import pandas as pd
                     import numpy as np
                     # Using NumPy ndarray
                     data = np.array([[1, 'Mayur', 25],
                                      [2, 'Esha', 30],

                                      [3, 'Vedant', 28]])
                     df = pd.DataFrame(data, columns=['ID', 'Name', 'Age'])
                     print(df)
                    Output:

                         ID        Name       Age
                     0    1       Mayur        25
                     1    2        Esha        30
                     2    3      Vedant        28
                  • •    Using a List of Dictionaries: You can create a DataFrame from a list of dictionaries where each dictionary represents
                     a row and keys represent column names.


                                                                                         Python Programming     209
   206   207   208   209   210   211   212   213   214   215   216