Found 10476 Articles for Python

Write a program in Python to count the records based on the designation in a given DataFrame

Vani Nalliappan
Updated on 24-Feb-2021 09:10:56

145 Views

Input −Assume, we have a DataFrame and group the records based on the designation is −Designation architect    1 programmer   2 scientist    2SolutionTo solve this, we will follow the below approaches.Define a DataFrameApply groupby method for Designation column and calculate the count as defined below,df.groupby(['Designation']).count()ExampleLet us see the following implementation to get a better understanding.import pandas as pd data = { 'Id':[1,2,3,4,5],          'Designation': ['architect','scientist','programmer','scientist','programmer']} df = pd.DataFrame(data) print("DataFrame is",df) print("groupby based on designation:") print(df.groupby(['Designation']).count())OutputDesignation architect    1 programmer   2 scientist    2

Write a program in Python to store the city and state names that start with ‘k’ in a given DataFrame into a new CSV file

Vani Nalliappan
Updated on 24-Feb-2021 09:07:57

681 Views

Input −Assume, we have DataFrame with City and State columns and find the city, state name startswith ‘k’ and store into another CSV file as shown below −City, State Kochi, KeralaSolutionTo solve this, we will follow the steps given below.Define a DataFrameCheck the city starts with ‘k’ as defined below, df[df['City'].str.startswith('K') & df['State'].str.startswith('K')] Finally, store the data in the ‘CSV’ file as below, df1.to_csv(‘test.csv’)ExampleLet us see the following implementation to get a better understanding.import pandas as pd import random as r data = { 'City': ['Chennai', 'Kochi', 'Kolkata'], 'State': ['Tamilnad', 'Kerala', 'WestBengal']} df = pd.DataFrame(data) print("DataFrame is", df) df1 = ... Read More

Write a Python code to select any one random row from a given DataFrame

Vani Nalliappan
Updated on 24-Feb-2021 09:05:45

435 Views

Input −Assume, sample DataFrame is,  Id Name 0 1 Adam 1 2 Michael 2 3 David 3 4 Jack 4 5 PeterOutputput −Random row is   Id    5 Name PeterSolutionTo solve this, we will follow the below approaches.Define a DataFrameCalculate the number of rows using df.shape[0] and assign to rows variable.set random_row value from randrange method as shown below.random_row = r.randrange(rows)Apply random_row inside iloc slicing to generate any random row in a DataFrame. It is defined below, df.iloc[random_row, :]ExampleLet us see the following implementation to get a better understanding.import pandas as pd import random as r data = { ... Read More

How can Tensorflow be used to train the model using Python?

AmitDiwan
Updated on 20-Feb-2021 08:07:11

186 Views

The model can be trained using the ‘train’ method in Tensorflow, where the epochs (number of times the data has to be trained to fit the model) and the training data are specified.Read More: What is TensorFlow and how Keras work with TensorFlow to create Neural Networks?We are using the Google Colaboratory to run the below code. Google Colab or Colaboratory helps run Python code over the browser and requires zero configuration and free access to GPUs (Graphical Processing Units). Colaboratory has been built on top of Jupyter Notebook.print("The model is being trained") epochs=12 history = model.fit(    train_ds,   ... Read More

How can Tensorflow be used to compile the model using Python?

AmitDiwan
Updated on 20-Feb-2021 08:05:40

266 Views

The created model in Tensorflow can be compiled using the ‘compile’ method. The loss is calculated using the ‘SparseCategoricalCrossentropy’ method.Read More: What is TensorFlow and how Keras work with TensorFlow to create Neural Networks?We are using the Google Colaboratory to run the below code. Google Colab or Colaboratory helps run Python code over the browser and requires zero configuration and free access to GPUs (Graphical Processing Units). Colaboratory has been built on top of Jupyter Notebook.print("The model is being compiled") model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),    metrics=['accuracy']) print("The architecture of the model") model.summary()Code credit: https://www.tensorflow.org/tutorials/images/classificationOutputThe model is being compiled The architecture of the ... Read More

How can Tensorflow be used to create a sequential model using Python?

AmitDiwan
Updated on 20-Feb-2021 08:02:57

148 Views

A sequential model can be created using the ‘Sequential’ API that uses the ‘ layers.experimental.preprocessing.Rescaling’ method. The other layers are specified while created the model.Read More: What is TensorFlow and how Keras work with TensorFlow to create Neural Networks?We will use the Keras Sequential API, which is helpful in building a sequential model that is used to work with a plain stack of layers, where every layer has exactly one input tensor and one output tensor.We are using the Google Colaboratory to run the below code. Google Colab or Colaboratory helps run Python code over the browser and requires zero ... Read More

How can Tensorflow be used to standardize the data using Python?

AmitDiwan
Updated on 20-Feb-2021 07:58:43

380 Views

We will be using the flowers dataset, which contains images of several thousands of flowers. It contains 5 sub-directories, and there is one sub-directory for every class. Once the flower dataset has been downloaded using the ‘get_file’ method, it will be loaded into the environment to work with it.The flower data can be standardized by introducing a normalization layer in the model. This layer is called the ‘Rescaling’ layer, which is applied to the entire dataset using the ‘map’ method.Read More: What is TensorFlow and how Keras work with TensorFlow to create Neural Networks?We are using the Google Colaboratory to ... Read More

How can Tensorflow be used to configure the dataset for performance?

AmitDiwan
Updated on 20-Feb-2021 07:51:43

946 Views

The flower dataset can be configured for performance with the help of buffer prefetch, shuffle method, and cache method. Buffered prefetching can be used to ensure that the data can be taken from disk without having I/O become blocking. Dataset.cache() keeps the images in memory after they have been loaded off disk during the first epoch. Dataset.prefetch() will overlap the data preprocessing and model execution while training.Read More: What is TensorFlow and how Keras work with TensorFlow to create Neural Networks?The Keras Sequential API is used, which is helpful in building a sequential model that is used to work with ... Read More

How can Tensorflow be used to visualize the data using Python?

AmitDiwan
Updated on 20-Feb-2021 07:56:00

294 Views

Let's say we have flower dataset. The flower dataset can be downloaded using a google API that basically links to the flower dataset. The ‘get_file’ method can be used to pass the API as a parameter. Once this is done, the data gets downloaded into the environment.It can be visualized using the ‘matplotlib’ library. The ‘imshow’ method is used to display the image on the console. Read More: What is TensorFlow and how Keras work with TensorFlow to create Neural Networks?We will use the Keras Sequential API, which is helpful in building a sequential model that is used to work with ... Read More

How can Tensorflow be used to pre-process the flower training dataset?

AmitDiwan
Updated on 20-Feb-2021 07:21:09

185 Views

The flower dataset can be pre-processed using the keras preprocessing API. It has a method named ‘image_dataset_from_directory’ that takes the validation set, the directory where data is stored, and other parameters to process the dataset.Read More: What is TensorFlow and how Keras work with TensorFlow to create Neural Networks?We will use the Keras Sequential API, which is helpful in building a sequential model that is used to work with a plain stack of layers, where every layer has exactly one input tensor and one output tensor. An image classifier is created using a keras.Sequential model, and data is loaded using ... Read More

Advertisements