Tag Archivio per: Check


There are multiple ways of checking the existing keys in a JavaScript object. Most of the ways include using methods from other packages. To do that, one generally has to first install that package and then work with the methods written inside it. But in this article, we will be working with the methods that come as default in JavaScript. So, let’s start with the first method.

Method 1: Using the “in” Operator to Find the Existence of a Key

We can use the “in” operator to check for a particular key in an object, just like we can use it to find the existence of a particular character in a string. To demonstrate this, we are going to need an object there create an object with the following lines of code:

var personObject = {
    firstName: «John»,
    lastName: «Doe»,
    age: 18,
    salary: 2200
}

 
As you can see, this object is about a person and includes details like the first name, last name, age, and salary. Suppose that we want to check whether or not the key “age” is present in our personObject. In that case, search for age in personObject and set the return value in a new variable:

existence = «age» in personObject;

 
After that, we can simply print the value inside the existence variable on the terminal using the console log function like:

 
After that, simply execute the program and observe the following result on the terminal:


The true value in the terminal means that the key age does exist in the object personObject.

After that, we also want to check for a key that is not present in the personObject. For this, we are going to use the in operator to find the key “martialStatus” in the personObject like:

existence = «martialStatus» in personObject;

 
And then again, we can simply pass this existence variable to the console log function to print the result on the terminal like:

 
Execute the program and observe the following result from the terminal:


As you can see, the result was false meaning that there is no such key as martialStatus inside our personObject.

Method 2: Using the “hasOwnProperty()” Method With the Object

In JavaScript, every object has some of the methods from its prototype. One such method is known as the hasOwnProperty(). This method takes in the key you want to search for in its argument and returns true or false depending upon the presence of the key in that object.

To demonstrate hasOwnProperty(), create an object using the following lines of code:

var car = {
  model: «2015»,
  make: «Porsche»,
  price: 328000,
  reviews: 4.8,
};

 
As you can already tell, the above lines are to create an object of a car. What we want to find is the presence of the key “make” in the object “car”. For this, apply the hasOwnProperty() method on the car object with the help of a dot operator and pass in the key “make” in its argument like:

existence = car.hasOwnProperty(«make»);

 
After that, simply pass the existence variable in the console log function to display the result on the terminal like:

 
Execute the program for the following outcome:


The output on the terminal is true, which means the car object contains the key make. After that, let’s check for the existence of the key “mileage” in our car object. For this, simply pass the key as mileage in the hasOwnProperty() method’s argument:

existence = car.hasOwnProperty(«mileage»);

 
To show the result on the terminal, simply pass the variable “existence” in the console log function:

 
Execute the program and observe the following output:


The output shows that there is no such key as mileage in the object car.

Conclusion

In JavaScript, we can quickly check the existence of a specific key inside an object with two different methods. The first methods include the use of the in operator, and it returns true if the existence is found otherwise, it returns false. The second method includes the use of a method of the JavaScript Object, which is the hasOwnProperty(). In its argument, you simply pass in the key you want to search for, and it returns true if the key is found in the object. Otherwise, it returns false.



Source link


There are multiple scenarios where you would generally want to look for the null variable because it can and will crash your whole application. Now that is something that we don’t want to happen. In JavaScript, you can easily check for a null variable with the help of a basic if-else statement. This article will demonstrate this with the help of examples.

Note: Most people confuse null variables with undefined and empty variables for being the same.

Example 1: Checking for Null variable with if – else statement

Simply start by creating a variable and setting its value equal to the keyword null with the following line:

 
Create another variable with some value in it with the help of the following line:

 
After that, we are going to create a function that will check variables for a null variable:

function checkNull(ourVar) {
  if (ourVar !== null) {
    console.log(«Not a Null variable»);
  } else {
    console.log(«Null variables Detected»);
  }
}

 
This function simply uses an if-else statement. After that, we are going to pass both our variables one by one to the function checkNull():

checkNull(x);
checkNull(y);

 
Executing this program will provide us with the following result:


The first line in the output is for the variable “x” and from the output we can determine that it is a null variable.

The second line is for the variable “y”; from the output, we can determine that it is not a null variable.

Example 2: Checking for other falsy values

The null value is known as a falsy value in JavaScript, and there are other falsy values in JavaScript. These falsy values include:

    • NaN
    • “” (an empty string)
    • undefined
    • false
    • And a few more.

However, they cannot be detected as null, and thus if-else statements cannot determine these variables as null.

To demonstrate this, create a few variables with these falsy values with the following lines of code:

var a = undefined;
var b = «»;
var c = NaN;
var d = false;
var e = 0;

 
After that, simply pass these variables one by one to the checkNull() function that we created in the previous example:

checkNull(a);
checkNull(b);
checkNull(c);
checkNull(d);
checkNull(e);

 
Executing the code will give the following output on the terminal:


All of these variables were considered to be non-null even though all belong to the same family which is “falsy values”.

Conclusion

In JavaScript, if-else statements can be used to determine whether a variable is a null variable or not. For this, we simply set the condition inside the if-else statement as (varName !== null), where varName is the variable identifier, we are checking. In this article, we created a function named checkNull() that determines whether the variable passed inside its argument is a null variable or not.



Source link


NIS, an abbreviation for Network Information Service, is a distributed database that helps you to maintain configuration files consistently in your networks. It provides a mainframe-client indexing service that store and circulates the server configuration information. Notably, it helps to manage the host and client names between machines in a PC network environment.

With the previous introductory information, it is right to conclude that NIS provides management and lookup services for the users within a network. But this is only possible merienda you add the user credentials to your database.

This article will provide a step-by-step guide on adding the users to your NIS system. Besides, it will also discuss how you can check the users within your system or find a specific user within the network.

Adding NIS Users to an NIS Domain

You can follow these steps to add a new user to your Linux NIS domain:

Step 1: Log in on the Master Server

You can only add the users if you have all the privileges of an administrator. Thus, begin by becoming an administrator on the master server. Notably, you can do this by creating your NIS profile during the NIS configuration.

Step 2: Create a New User

Proceed to create a new user using the useradd command. The utility creates the entries with relevant user credentials in the /etc/passwd file and the /etc/shadow profile. The following command illustrates this step and you can replace the userID with the login ID of the user you intend to add:


Step 3: Create a Password for the New User

Use the yppasswd command to create a password for the new user. The user will use this password whenever they want to log in. In the following illustration, the UserID specifies the user whose password you are creating. This step is important to ensure that the password created is lockable and useable during logins. The password created with the initial useradd command is not lockable.


Step 4: Copy the Entry into the Master Server

The next step is to copy the new user credentials into your master server’s passwd map files. Your master server’s source files should not be in a /etc file. Proceed to copy the newly created files from both the /etc/passwd and /etc/shadow files onto the passwd input file on your server.

For instance, if you add a new user named Ken, you copy the following line from the /etc/passwd to the passwd input map file:


Similarly, the following line is what you would copy from /etc/shadow to your passwd input map files:


Step 5: Delete Entries from /etc/shadow and /etc/passwd Input Files

It is trascendental to ensure that the Makefile correctly indicates the location of the copied password input file.

Merienda you copy the entries to a map source file stored in a different directory and ascertain their location, you should proceed and delete the entries in both /etc/shadow and /etc/passwd. This action is entirely for security purposes. Delete the entries using the userdel utility on your master server as indicated in the following:


Step 6: Update Your NIS Passwd Maps

Merienda your input files in the master server are updated, you can update the passwd maps using the following command:


The previous steps help add a new user to your NIS system. Merienda through, inform the new user of the initial password assigned to them. They can then login and change the password appropriately.

Finding Users in Your NIS Domain

You can also look up the users in your NIS domain. These two methods come in handy from time to time.

a. Obtaining a List of All Users in the Domain

The ypcat passwd command displays a complete list of the users in your system. You can use it as in the following illustration:

b. Finding a Specific User

You can identify a specific user from your system by running the following command:


For example, you can look up the user named Ken in the NIS system by replacing the “username” in the command with Ken.

If the user named Ken is available, you will receive the following result:


But you can expect the following result in case the user does not exist:

Conclusion

The previous illustrations show how you can add the users to your NIS system. It also shows how you can search and find the users from your systems.

Sources:



Source link


Occasionally, installing fresh packages daily may be necessary when working in a Linux environment. To install new software, you must determine how much RAM is available. Therefore, you should be able to examine the RAM or memory installed and available on your system.

This post will examine a few key commands for CentOS 8 that help determine how much memory or RAM is available.

Prerequisites

To check the memory usage, you should have sudo privileges.

How To Check Memory Usage Details Using GUI on CentOS 8

You can easily carry out the following action if you wish to check memory usage details using the graphical user interface (GUI). In the search box for the application, enter “system preceptor”.

You can quickly check the RAM usage by selecting the “Resources” tab.

Linux Commands Used To Check the Memory Usage Details on CentOS 8

The five different methods available can help determine how much memory is in use. These methods are listed:

  1. Free command
  2. Cat command
  3. vmstat command
  4. Htop command
  5. Top command

Check Memory Usage Details Using the Free Command

The previous image displayed contains several concepts, each of which we will define individually.

  • Used memory may be calculated using the formula used memory = total – free – buffer/cache.
  • The total reflects the total memory installed on your machine.
  • Free displays the memory that is not in use.
  • Shared displays the amount of memory that is shared by various programs.
  • Buffers the memory that the OS kernel has set aside. When a process demands additional memory, this memory is allocated as buffers.
  • Cached memory is used to store recently accessed files in RAM.
  • buff/cache Memory cache + buffers
  • Available displays memory that can be used to begin new processes without swapping.

The information displayed in the previous screenshot, such as that under the words used, available, and swap memory, is in kilobytes.

You may examine the complete description and all the options of the free command by using the following command:

Check Memory Usage Details Using the “cat” Command

First, open the terminal window and type “cat /proc/meminfo”. This command displays the total memory usage and available memory information from a file “/proc/meminfo”.

This command displays the real-time details of memory usage and the information about shared memory, which is used by the buffers and kernel.

Check Memory Statistics Using the vmstat Command

To view comprehensive posible memory statistics, use the vmstat command.

The memory, system processes, CPU activity, paging, block IO, and traps are all exposed by this command.

Display Memory Usage Details Using the htop Command

Like the top command, the htop command displays information. The htop command offers a user-friendly interface and improved control options.

The htop command has an interactive interface and can scroll the page horizontally and vertically. It also uses colors to present its output and provides a complete command-line environment for all processes. To exit the current window, press “Ctrl+c”.

The following information will appear on your terminal:

  1. The information summary and visual text counts are in the top area.
  2. The comprehensive information for each procedure is shown in the middle part. It is simple to carry out the various tasks on each distinct process.
  3. You can rapidly configure and manipulate the processes without using any commands, thanks to the list of all shortcuts at the bottom of the displayed window.

The following command can be used to install the htop utility if it isn’t already on your CentOS 8 system:

Check Memory Usage Details Using the top Command

The command-line tool top helps look at how much memory and CPU each process uses. It presents details about items, such as Uptime, media load, tasks running, user logged-in information, CPU utilization, swap and memory usage, and system processes.

The top command automatically updates the information on the terminal, allowing you to track the processes’ use of RAM in real-time.

Conclusion

This article has shown us how to preceptor the memory usage details on the CentOS 8 system. Additionally, we have run other commands to display the memory information, including cat, free, vmstat, top, and htop. You may quickly find out information about your system’s RAM and CPU by using these instructions.



Source link


PowerShell supports various operations on files. Prior to the operation, it is recommended to check the existence of the file. To do so, PowerShell offers various cmdlets and methods. This post analyzes and provides a detailed usage of the cmdlets/methods to check the existence of the file. To check whether a file exists or not we will use multiple methods to determine the existence of the file in the specific location. We will explain the four methods to check the existence of the file which will enable you to check the existence of the file in PowerShell

Method 1: Use the Test-path cmdlet to check the existence of the file

Test-Path cmdlet looks for the path and returns a Boolean value. Test-Path will return true if the path is correct, and if the path is not found then it returns false. The syntax followed by the Test-Path cmdlet is provided below:

Syntax

> Test-Path -Path <FilePath> <parameters>

In the above syntax

  • <FilePath>: it refers to the location of the file
  • Path: used to specify a path
  • <Parameters>: defines the parameters for additional functionality

Example
This program will check the existence of the file using the Test-Path method. It is recommended to provide the absolute path of the file as we did here.

> TestPath Path «C:/Docs/PS.txt» PathType Leaf

The output is True which means the file exists. It is observed that the “Test-Path” cmdlet has returned true which states that the file exists.

Method 2: Use Get-Item to check the existence of the file

The Get-Item cmdlet of PowerShell is used to get items in the specified location. The syntax of the Get-Item cmdlet is provided below:

Syntax

The syntax elements are described as:

  • Get-Item: uses the wildcard character (*) to get everything of the specified item.
  • <FilePath>: it refers to the location of the file

Example
This program will also check the existence of the file by using the Get-Item method.

> Get-Item C:/Docs/PS.txt

The Get-Item has printed the details of the file which states that the file exists at the specified path.

Method 3: Use the Get-ChildItem cmdlet to check the existence of the file

This method gets the item as well as child items from more than one specified path. If the file exists, it will show the file details and throw an error in case the file is not present.

The syntax of the Get-ChildItem cmdlet is provided below:

Syntax

> Get-ChildItem -Path <FilePath>

The syntax elements are explained a:

  • Get-ChildItem: gets the content of a folder or registry key
  • Path: used to specify a path
  • <FilePath>: it refers to the location of the file

Example
This program will check the existence of the file using the Get-Childitem method.

> Get-Childitem -Path C:/Docs/PS.txt

The output shows the file details which means the file exists.

Method 4: Use the System.IO.file method to check the existence of the file

The [System.IO.File]::Exists(File) method also checks the existence of the file. This method provides the result in a Boolean(true/false) value. The following syntax is followed to apply this method:

Syntax

> [System.IO.File]::Exists(<FilePath>)

The above syntax will be used to check the existence of a file by specifying the path of the file in the <FilePath> parameter.

Example
Here, the [System.IO.File]::Exists method is exercised to check the file is present at the given path or not.

> [System.IO.File]::Exists(«C:/Docs/PS.txt»)

The output is True which means the file exists.

Congrats! You have learned to check the existence of the file in PowerShell

Conclusion

PowerShell cmdlets such as Get-ChildItem, Get-Item, and Test-Path can be used to check the existence of the file. Moreover, PowerShell also provides a .NET supported method “[System.IO.file]::Exists” to check the existence of a file. In this post, we have demonstrated various possible methods to check the existence of the file. The usage of these three cmdlets as well as the method is explained with the help of examples.



Source link


In Python, PySpark is a Spark module used to provide a similar kind of processing like spark.

RDD stands for Resilient Distributed Datasets. We can call RDD a fundamental data structure in Apache Spark.

Syntax:

1

spark_app.sparkContext.parallelize(data)

We can display the data in a tabular format. The data structure used is DataFrame.Tabular format means it stores data in rows and columns.

Syntax:

In PySpark, we can create a DataFrame from spark app with the createDataFrame() method.

Syntax:

1

Spark_app.createDataFrame(input_data,columns)

Where input_data may be a dictionary or a list to create a dataframe from this data, and if the input_data is a list of dictionaries, then the columns are not needed. If it is a nested list, we have to provide the column names.

Now, let’s discuss how to check the given data in PySpark RDD or DataFrame.

Creation of PySpark RDD:

In this example, we will create an RDD named students and display using collect() action.

#import the pyspark module

import pyspark

#import SparkSession for creating a session

from pyspark.sql import SparkSession

# import RDD from pyspark.rdd

from pyspark.rdd import RDD

 

#create an app named linuxhint

spark_app = SparkSession.builder.appName(‘linuxhint’).getOrCreate()

 

# create student data with 5 rows and 6 attributes

students =spark_app.sparkContext.parallelize([
   {‘rollno’:‘001’,‘name’:‘sravan’,‘age’:23,‘height’:5.79,‘weight’:67,‘address’:‘guntur’},

 {‘rollno’:‘002’,‘name’:‘ojaswi’,‘age’:16,‘height’:3.79,‘weight’:34,‘address’:‘hyd’},

 {‘rollno’:‘003’,‘name’:‘gnanesh chowdary’,‘age’:7,‘height’:2.79,‘weight’:17,‘address’:‘patna’},

 {‘rollno’:‘004’,‘name’:‘rohith’,‘age’:9,‘height’:3.69,‘weight’:28,‘address’:‘hyd’},

 {‘rollno’:‘005’,‘name’:‘sridevi’,‘age’:37,‘height’:5.59,‘weight’:54,‘address’:‘hyd’}])

 

#display the RDD using collect()

print(students.collect())

Output:

[{‘rollno’: ‘001’, ‘name’: ‘sravan’, ‘age’: 23, ‘height’: 5.79, ‘weight’: 67, ‘address’: ‘guntur’},

{‘rollno’: ‘002’, ‘name’: ‘ojaswi’, ‘age’: 16, ‘height’: 3.79, ‘weight’: 34, ‘address’: ‘hyd’},

{‘rollno’: ‘003’, ‘name’: ‘gnanesh chowdary’, ‘age’: 7, ‘height’: 2.79, ‘weight’: 17, ‘address’: ‘patna’},

{‘rollno’: ‘004’, ‘name’: ‘rohith’, ‘age’: 9, ‘height’: 3.69, ‘weight’: 28, ‘address’: ‘hyd’},

{‘rollno’: ‘005’, ‘name’: ‘sridevi’, ‘age’: 37, ‘height’: 5.59, ‘weight’: 54, ‘address’: ‘hyd’}]

Creation of PySpark DataFrame:

In this example, we will create a DataFrame named df from the students’ data and display it using the show() method.

#import the pyspark module

import pyspark

#import SparkSession for creating a session

from pyspark.sql import SparkSession

#import the col function

from pyspark.sql.functions import col

 

#create an app named linuxhint

spark_app = SparkSession.builder.appName(‘linuxhint’).getOrCreate()

 

# create student data with 5 rows and 6 attributes

students =[

    {‘rollno’:‘001’,‘name’:‘sravan’,‘age’:23,‘height’:5.79,‘weight’:67,‘address’:‘guntur’},

  {‘rollno’:‘002’,‘name’:‘ojaswi’,‘age’:16,‘height’:3.79,‘weight’:34,‘address’:‘hyd’},

  {‘rollno’:‘003’,‘name’:‘gnanesh chowdary’,‘age’:7,‘height’:2.79,‘weight’:17,‘address’:‘patna’},

  {‘rollno’:‘004’,‘name’:‘rohith’,‘age’:9,‘height’:3.69,‘weight’:28,‘address’:‘hyd’},

  {‘rollno’:‘005’,‘name’:‘sridevi’,‘age’:37,‘height’:5.59,‘weight’:54,‘address’:‘hyd’}]

 

# create the dataframe

df = spark_app.createDataFrame( students)

 

#display the dataframe

df.show()

Output:

Method 1 : isinstance()

In Python, isinstance() method is used to compare the given object(data) with the type(RDD/DataFrame)

Syntax:

1

isinstance(object,RDD/DataFrame)

It takes two parameters:

Parameters:

  1. object refers to the data
  2. RDD is the type available in pyspark.rdd module and DataFrame is the type available in pyspark.sql module

It will return Boolean values (True/False).

Suppose the data is RDD and the type is also RDD, then it will return True, otherwise it will return False.

Similarly, if the data is DataFrame and type is also DataFrame, then it will return True, otherwise it will return False.

Example 1:

Check for RDD object

In this example, we will apply isinstance() for RDD object.

#import the pyspark module

import pyspark

#import SparkSession  and DataFrame for creating a session

from pyspark.sql import SparkSession,DataFrame

# import RDD from pyspark.rdd

from pyspark.rdd import RDD

 

#create an app named linuxhint

spark_app = SparkSession.builder.appName(‘linuxhint’).getOrCreate()

 

# create student data with 5 rows and 6 attributes

students =spark_app.sparkContext.parallelize([
   {‘rollno’:‘001’,‘name’:‘sravan’,‘age’:23,‘height’:5.79,‘weight’:67,‘address’:‘guntur’},

  {‘rollno’:‘002’,‘name’:‘ojaswi’,‘age’:16,‘height’:3.79,‘weight’:34,‘address’:‘hyd’},

  {‘rollno’:‘003’,‘name’:‘gnanesh chowdary’,‘age’:7,‘height’:2.79,‘weight’:17,‘address’:‘patna’},

  {‘rollno’:‘004’,‘name’:‘rohith’,‘age’:9,‘height’:3.69,‘weight’:28,‘address’:‘hyd’},

  {‘rollno’:‘005’,‘name’:‘sridevi’,‘age’:37,‘height’:5.59,‘weight’:54,‘address’:‘hyd’}])

 

#check if the students object is RDD

print(isinstance(students,RDD))

 

#check if the students object is DataFrame

print(isinstance(students,DataFrame))

Output:

First, we compared students with RDD; it returned True because it is an RDD; and then we compared students with DataFrame, it returned False because it is an RDD (not a DataFrame).

Example 2:

Check for DataFrame object

In this example, we will apply isinstance() for the DataFrame object.

#import the pyspark module

import pyspark

#import SparkSession,DataFrame for creating a session

from pyspark.sql import SparkSession,DataFrame

#import the col function

from pyspark.sql.functions import col

# import RDD from pyspark.rdd

from pyspark.rdd import RDD

 

#create an app named linuxhint

spark_app = SparkSession.builder.appName(‘linuxhint’).getOrCreate()

 

# create student data with 5 rows and 6 attributes

students =[

   {‘rollno’:‘001’,‘name’:‘sravan’,‘age’:23,‘height’:5.79,‘weight’:67,‘address’:‘guntur’},

  {‘rollno’:‘002’,‘name’:‘ojaswi’,‘age’:16,‘height’:3.79,‘weight’:34,‘address’:‘hyd’},

  {‘rollno’:‘003’,‘name’:‘gnanesh chowdary’,‘age’:7,‘height’:2.79,‘weight’:17,‘address’:‘patna’},

  {‘rollno’:‘004’,‘name’:‘rohith’,‘age’:9,‘height’:3.69,‘weight’:28,‘address’:‘hyd’},

  {‘rollno’:‘005’,‘name’:‘sridevi’,‘age’:37,‘height’:5.59,‘weight’:54,‘address’:‘hyd’}]

 

# create the dataframe

df = spark_app.createDataFrame( students)

 

#check if the df  is RDD

print(isinstance(df,RDD))

 

#check if the df  is DataFrame

print(isinstance(df,DataFrame))

Output:

First, we compared df with RDD; it returned False because it is a DataFrame and then we compared df with DataFrame; it returned True because it is a DataFrame (not an RDD).

Method 2 : type()

In Python, the type() method returns the class of the specified object. It takes object as a parameter.

Syntax:

Example 1:

Check for an RDD object.

We will apply type() to the RDD object.

#import the pyspark module

import pyspark

#import SparkSession  for creating a session

from pyspark.sql import SparkSession

# import RDD from pyspark.rdd

from pyspark.rdd import RDD

 

#create an app named linuxhint

spark_app = SparkSession.builder.appName(‘linuxhint’).getOrCreate()

 

# create student data with 5 rows and 6 attributes

students =spark_app.sparkContext.parallelize([

   {‘rollno’:‘001’,‘name’:‘sravan’,‘age’:23,‘height’:5.79,‘weight’:67,‘address’:‘guntur’},

  {‘rollno’:‘002’,‘name’:‘ojaswi’,‘age’:16,‘height’:3.79,‘weight’:34,‘address’:‘hyd’},

  {‘rollno’:‘003’,‘name’:‘gnanesh chowdary’,‘age’:7,‘height’:2.79,‘weight’:17,‘address’:‘patna’},

  {‘rollno’:‘004’,‘name’:‘rohith’,‘age’:9,‘height’:3.69,‘weight’:28,‘address’:‘hyd’},

  {‘rollno’:‘005’,‘name’:‘sridevi’,‘age’:37,‘height’:5.59,‘weight’:54,‘address’:‘hyd’}])

 

#check the type of students

print(type(students))

Output:

1

<class ‘pyspark.rdd.RDD’>

We can see that class RDD is returned.

Example 2:

Check for DataFrame object.

We will apply type() on the DataFrame object.

#import the pyspark module

import pyspark

#import SparkSession for creating a session

from pyspark.sql import SparkSession

#import the col function

from pyspark.sql.functions import col

 

 

#create an app named linuxhint

spark_app = SparkSession.builder.appName(‘linuxhint’).getOrCreate()

 

# create student data with 5 rows and 6 attributes

students =[

  {‘rollno’:‘001’,‘name’:‘sravan’,‘age’:23,‘height’:5.79,‘weight’:67,‘address’:‘guntur’},

  {‘rollno’:‘002’,‘name’:‘ojaswi’,‘age’:16,‘height’:3.79,‘weight’:34,‘address’:‘hyd’},

  {‘rollno’:‘003’,‘name’:‘gnanesh chowdary’,‘age’:7,‘height’:2.79,‘weight’:17,‘address’:‘patna’},

  {‘rollno’:‘004’,‘name’:‘rohith’,‘age’:9,‘height’:3.69,‘weight’:28,‘address’:‘hyd’},

  {‘rollno’:‘005’,‘name’:‘sridevi’,‘age’:37,‘height’:5.59,‘weight’:54,‘address’:‘hyd’}]

 

# create the dataframe

df = spark_app.createDataFrame( students)

 

#check the type of df

print(type(df))

Output:

1

<class ‘pyspark.sql.dataframe.DataFrame’>

We can see that class DataFrame is returned.

Conclusion

In the above article, we saw two ways to check if the given data or object is an RDD or DataFrame using isinstance() and type(). You must note that isinstance() results in boolean values based on the given object – if the object type is the same, then it will return True, otherwise False. And type() is used to return the class of the given data or object.



Source link


For this one, we will explore how to get the data type of a specific column in a Pandas DataFrame.

Sample

Let us start by creating a sample DataFrame:

# import pandas
import pandas as pd
df = pd.DataFrame({
    ‘salary’: [120000, 100000, 90000, 110000, 120000, 100000, 56000],
    ‘department’: [‘game developer’, ‘database developer’, ‘front-end developer’, ‘full-stack developer’, ‘database developer’, ‘security researcher’, ‘cloud-engineer’],
    ‘rating’: [4.3, 4.4, 4.3, 3.3, 4.3, 5.0, 4.4]},
    index=[‘Alice’, ‘Michael’, ‘Joshua’, ‘Patricia’, ‘Peter’, ‘Jeff’, ‘Ruth’])
print(df)

The above should create a DataFrame with sample data as shown:

Pandas dtype Attribute

The most straightforward way to get the column’s data type in Pandas is to use the dtypes attribute.

The syntax is as shown:

The attribute returns each column and its corresponding data type.

An example is as shown:

The above should return the columns and their data types as shown:

salary          int64
department     object
rating        float64

If you want to get the data type of a specific column, you can pass the column name as an index as shown:

This should return the data type of the salary column as shown:

Pandas Column Info

Pandas also provide us with the info() method. It allows us to get detailed information about the columns within a Pandas DataFrame.

The syntax is as shown:

DataFrame.info(verbose=None, buf=None, max_cols=None, memory_usage=None, show_counts=None, null_counts=None)

It allows you to fetch the name of the columns, data type, number of non-null elements, etc.

An example is as shown:

This should return:

The above shows detailed information about the columns in the DataFrame, including the data type.

Conclusion

This tutorial covers two methods you can use to fetch the data type of a column in a Pandas DataFrame.

Thanks for reading!!



Source link