Showing posts with label dataframe. Show all posts
Showing posts with label dataframe. Show all posts

December 30, 2021

Top 20 Python Pandas Interview Questions and Answers


            Pandas is a Python library that provides high-performance, easy-to-use data structures and data analysis tools for the Python programming language. It is open-source and BSD-licensed. Python with Pandas is utilised in a variety of academic and commercial disciplines, including finance, economics, statistics, analytics, and more. 

Data analysis necessitates a great deal of processing, such as restructuring, cleansing, or combining, among other things. Numpy, Scipy, Cython, and Panda are just a few of the quick data processing tools available. However, we favour Pandas since they are faster, easier, and more expressive than other tools.


Python Interview Questions & Answers


Ques. 1): What is Pandas? What is the purpose of Python pandas?

Answer:

Pandas is a Python module that provides quick, versatile, and expressive data structures that make working with "relational" or "labelled" data simple and intuitive. Its goal is to serve as the foundation for undertaking realistic, real-world data analysis in Python.

Pandas is a data manipulation and analysis software library for the Python programming language. It includes data structures and methods for manipulating numerical tables and time series, in particular. Pandas is open-source software distributed under the BSD three-clause licence.

 

Ques. 2): Mention the many types of data structures available in Pandas?

Answer:

The pandas library supports two data structures: Series and DataFrames. Numpy is used to construct both data structures. In pandas, a Series is a one-dimensional data structure, while a DataFrame is a two-dimensional data structure. Panel is another axis label that is a three-dimensional data structure that comprises items, major axis, and minor axis.

 

Ques. 3): What are the key features of pandas library ? What is pandas Used For ?

Answer:

There are various features in pandas library and some of them are mentioned below

Data Alignment

Memory Efficient

Reshaping

Merge and join

Time Series

This library is developed in Python and can be used to do data processing, data analysis, and other tasks. To manipulate time series and numerical tables, the library contains numerous operations as well as data structures.

 

Ques. 4): What is Pandas NumPy?

Answer:

Pandas Numpy is an open-source Python module that allows you to work with a huge number of datasets. For scientific computing with Python, it has a powerful N-dimensional array object and complex mathematical methods.

Fourier transformations, linear algebra, and random number capabilities are some of Numpy's most popular features. It also includes integration tools for C/C++ and Fortran programming.

 

Ques. 5): In Pandas, what is a Time Series?

Answer:

An ordered sequence of data that depicts how a quantity evolves over time is known as a time series. For all fields, pandas has a wide range of capabilities and tools for working with time series data.

pandas supports:

Taking time series data from a variety of sources and formats and parsing it

Create a series of dates and time ranges with a set frequency.

Manipulation and conversion of date and time with timezone data

A time series is resampled or converted to a specific frequency.

Using absolute or relative time increments to do date and time arithmetic.

 

Ques. 6): In pandas, what is a DataFrame?

Answer:

Pandas DataFrame is a possibly heterogeneous two-dimensional size-mutable tabular data format with labelled axes (rows and columns). A data frame is a two-dimensional data structure in which data is organised in rows and columns in a tabular format. The data, rows, and columns are the three main components of a Pandas DataFrame.

Creating a Pandas DataFrame-

A Pandas DataFrame is built in the real world by loading datasets from existing storage, which can be a SQL database, a CSV file, or an Excel file. Pandas DataFrames can be made from lists, dictionaries, and lists of dictionaries, among other things. A dataframe can be constructed in a variety of ways.  

Creating a dataframe using List: DataFrame can be created using a single list or a list of lists.

 

Ques. 7): Explain Series In pandas. How To Create Copy Of Series In pandas?

Answer:

Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.). The axis labels are collectively referred to as the index. The basic method to create a Series is to call:

>>> s = pd.Series(data, index=index), where the data can be a Python dict, an ndarray or a scalar value.

To create a copy in pandas, we can call copy() function on a series such that

s2=s1.copy() will create copy of series s1 in a new series s2.

 

Ques. 8): How will you create an empty DataFrame in pandas?

Answer:

To create a completely empty Pandas dataframe, we use do the following:

import pandas as pd

MyEmptydf = pd.DataFrame()

This will create an empty dataframe with no columns or rows.

To create an empty dataframe with three empty column (columns X, Y and Z), we do:

df = pd.DataFrame(columns=[‘X’, ‘Y’, ‘Z’])

 

Ques. 9): What is Python pandas vectorization?

Answer:

The process of executing operations on the full array is known as vectorization. This is done to reduce the number of times the functions iterate. Pandas has a number of vectorized functions, such as aggregations and string functions, that are designed to work with series and DataFrames especially. To perform the operations quickly, it is preferable to use the vectorized pandas functions.

 

Ques. 10):  range ()  vs and xrange () functions in Python?

Answer:

In Python 2 we have the following two functions to produce a list of numbers within a given range.

range()

xrange()

in Python 3, xrange() is deprecated, i.e. xrange() is removed from python 3.x.

Now In Python 3, we have only one function to produce the numbers within a given range i.e. range() function.

But, range() function of python 3 works same as xrange() of python 2 (i.e. internal implementation of range() function of python 3 is same as xrange() of Python 2).

So The difference between range() and xrange() functions becomes relevant only when you are using python 2.

range() and xrange() function values

a). range() creates a list i.e., range returns a Python list object, for example, range (1,500,1) will create a python list of 499 integers in memory. Remember, range() generates all numbers at once.

b).xrange() functions returns an xrange object that evaluates lazily. That means xrange only stores the range arguments and generates the numbers on demand. It doesn’t generate all numbers at once like range(). Furthermore, this object only supports indexing, iteration, and the len() function.

On the other hand xrange() generates the numbers on demand. That means it produces number one by one as for loop moves to the next number. In every iteration of for loop, it generates the next number and assigns it to the iterator variable of for loop.

 

Ques. 11):  What does categorical data mean in Pandas?

Answer:

Categorical data is a Pandas data type that correlates to a statistical categorical variable. A categorical variable is one that has a restricted number of possible values, which is usually fixed. Gender, country of origin, blood type, social status, observation time, and Likert scale ratings are just a few examples. Categorical data values are either in categories or np.nan.This data type is useful in the following cases:

It is useful for a string variable that consists of only a few different values. If we want to save some memory, we can convert a string variable to a categorical variable.

It is useful for the lexical order of a variable that is not the same as the logical order (“one”, “two”, “three”) By converting into a categorical and specify an order on the categories, sorting and min/max is responsible for using the logical order instead of the lexical order.

It is useful as a signal to other Python libraries because this column should be treated as a categorical variable.

 

Ques. 12): To a Pandas DataFrame, how do you add an index, a row, or a column?

Answer:

Adding an Index into a DataFrame: If you create a DataFrame with Pandas, you can add the inputs to the index argument. It will ensure that you get the index you want. If no inputs are specified, the DataFrame has a numerically valued index that starts at 0 and terminates on the DataFrame's last row.

Increasing the number of rows in a DataFrame: To insert rows in the DataFrame, we can use the.loc, iloc, and ix commands.

The loc is primarily used for our index's labels. It can be seen as if we insert in loc[4], which means we're seeking for DataFrame items with an index of 4.

The ix is a complex case because if the index is integer-based, we pass a label to ix. The ix[4] means that we are looking in the DataFrame for those values that have an index labeled 4. However, if the index is not only integer-based, ix will deal with the positions as iloc.

 

Ques. 13): How to Delete Indices, Rows or Columns From a Pandas Data Frame?

Answer:

Deleting an Index from Your DataFrame

If you want to remove the index from the DataFrame, you should have to do the following:

Reset the index of DataFrame.

Executing del df.index.name to remove the index name.

Remove duplicate index values by resetting the index and drop the duplicate values from the index column.

Remove an index with a row.

Deleting a Column from Your DataFrame

You can use the drop() method for deleting a column from the DataFrame.

The axis argument that is passed to the drop() method is either 0 if it indicates the rows and 1 if it drops the columns.

You can pass the argument inplace and set it to True to delete the column without reassign the DataFrame.

You can also delete the duplicate values from the column by using the drop_duplicates() method.

Removing a Row from Your DataFrame

By using df.drop_duplicates(), we can remove duplicate rows from the DataFrame.

You can use the drop() method to specify the index of the rows that we want to remove from the DataFrame.

 

Ques. 14): How to convert String to date?

Answer:

The below code demonstrates how to convert the string to date:

From datetime import datetime

# Define dates as the strings

dmy_str1 = ‘Wednesday, July 14, 2018’

dmy_str2 = ’14/7/17′

dmy_str3 = ’14-07-2017′

# Define dates as the datetime objects

dmy_dt1 = datetime.strptime(date_str1, ‘%A, %B %d, %Y’)

dmy_dt2 = datetime.strptime(date_str2, ‘%m/%d/%y’)

dmy_dt3 = datetime.strptime(date_str3, ‘%m-%d-%Y’)

#Print the converted dates

print(dmy_dt1)

print(dmy_dt2)

print(dmy_dt3)

 

Ques. 15): What exactly is the Pandas Index?

Answer:

Pandas indexing is as follows:

In pandas, indexing simply involves picking specific rows and columns of data from a DataFrame. Selecting all of the rows and some of the columns, part of the rows and all of the columns, or some of each of the rows and columns is what indexing entails. Subset selection is another name for indexing.

Using [],.loc[],.iloc[],.ix[] for Pandas indexing

A DataFrame's items, rows, and columns can be extracted in a variety of methods. In Pandas, there are some indexing methods that can be used to retrieve an element from a DataFrame. These indexing systems look to be fairly similar on the surface, however they perform extremely differently. Pandas supports four different methods of multi-axes indexing:

Dataframe.[ ] ; This function also known as indexing operator

Dataframe.loc[ ] : This function is used for labels.

Dataframe.iloc[ ] : This function is used for positions or integer based

Dataframe.ix[] : This function is used for both label and integer based

Collectively, they are called the indexers. These are by far the most common ways to index data. These are four function which help in getting the elements, rows, and columns from a DataFrame.

 

Ques. 16): Define ReIndexing?

Answer:

Reindexing changes the row labels and column labels of a DataFrame. To reindex means to conform the data to match a given set of labels along a particular axis.

Multiple operations can be accomplished through indexing like −

Reorder the existing data to match a new set of labels.

Insert missing value (NA) markers in label locations where no data for the label existed.

 

Ques. 17): How to Set the index?

Answer:

Python is an excellent language for data analysis, thanks to its vast ecosystem of data-centric Python packages. One of these packages is Pandas, which makes importing and analysing data a lot easier.

Pandas set index() is a function for setting the index of a Data Frame from a List, Series, or Data Frame. A data frame's index column can also be set while it's being created. However, because a data frame might be made up of two or more data frames, the index can be altered later using this method.

Syntax:

DataFrame.set_index(keys, drop=True, append=False, inplace=False, verify_integrity=False

 

Ques. 18): Define GroupBy in Pandas?

Answer:

Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.

Pandas dataframe.groupby() function is used to split the data into groups based on some criteria. pandas objects can be split on any of their axes. The abstract definition of grouping is to provide a mapping of labels to group names.

Syntax: DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, **kwargs)

Parameters :

by : mapping, function, str, or iterable

axis : int, default 0

level : If the axis is a MultiIndex (hierarchical), group by a particular level or levels

as_index : For aggregated output, return object with group labels as the index. Only relevant for DataFrame input. as_index=False is effectively “SQL-style” grouped output

sort : Sort group keys. Get better performance by turning this off. Note this does not influence the order of observations within each group. groupby preserves the order of rows within each group.

group_keys : When calling apply, add group keys to index to identify pieces

squeeze : Reduce the dimensionality of the return type if possible, otherwise return a consistent type

Returns : GroupBy object

 

Ques. 19): How will you add a scalar column with same value for all rows to a pandas DataFrame?

Answer:

Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.

Dataframe.add() method is used for addition of dataframe and other, element-wise (binary operator add). Equivalent to dataframe + other, but with support to substitute a fill_value for missing data in one of the inputs.

Syntax: DataFrame.add(other, axis=’columns’, level=None, fill_value=None)

Parameters:

other :Series, DataFrame, or constant

axis :{0, 1, ‘index’, ‘columns’} For Series input, axis to match Series index on

fill_value : [None or float value, default None] Fill missing (NaN) values with this value. If both DataFrame locations are missing, the result will be missing.

level : [int or name] Broadcast across a level, matching Index values on the passed MultiIndex level

Returns: result DataFrame

 

Ques. 20): In pandas, how can you see if a DataFrame is empty?

Answer:

Pandas DataFrame is a possibly heterogeneous two-dimensional size-mutable tabular data format with labelled axes (rows and columns). Both the row and column labels align for arithmetic operations. It can be viewed of as a container for Series items, similar to a dict. The Pandas' fundamental data structure is this.

Pandas DataFrame is a dataframe for Pandas.

The empty attribute determines whether or not the dataframe is empty. If the dataframe is empty, it returns True; otherwise, it returns False.

Syntax: DataFrame.empty

Parameter : None

Returns : bool

 


November 17, 2021

Top 20 Apache Spark Interview Questions & Answers

  

Ques: 1). What is Apache Spark?

Answer:

Apache Spark is an open-source real-time processing cluster computing framework. It has a vibrant open-source community and is now the most active Apache project. Spark is a programming language that allows you to programme large clusters with implicit data parallelism and fault tolerance.

Spark is one of the Apache Software Foundation's most successful projects. Spark has unquestionably established itself as the market leader in Big Data processing. Spark is used by many enterprises on clusters with thousands of nodes. Spark is now used by large companies like as Amazon, eBay, and Yahoo!


BlockChain Interview Question and Answers


Ques: 2). What advantages does Spark have over MapReduce?

Answer:

Compared to MapReduce, Spark has the following advantages:

Spark implements processing 10 to 100 times quicker than Hadoop MapReduce due to the availability of in-memory processing, whereas MapReduce uses persistence storage for any of the data processing activities.

Unlike Hadoop, Spark has built-in libraries that allow it to do a variety of functions from the same core, including as batch processing, steaming, machine learning, and interactive SQL queries. Hadoop, on the other hand, only supports batch processing.

Hadoop is heavily reliant on discs, but Spark encourages caching and data storage in memory. Spark is capable of performing computations multiple times on the same dataset. This is called iterative computation while there is no iterative computing implemented by Hadoop.

Apache Hive Interview Questions & Answers

Ques: 3). What exactly is YARN?

Answer:

YARN is a fundamental element in Spark, similar to Hadoop, in that it provides a central and resource management platform for delivering scalable operations across the cluster. YARN, like Mesos, is a distributed container manager, but Spark is a data processing tool. Spark can be run on YARN in the same way that Hadoop Map Reduce can. Running Spark on YARN needs the use of a Spark binary distribution with YARN support.

 Apache Ambari interview Questions & Answers

Ques: 4). What's the difference between an RDD, a Dataframe, and a Dataset?

Answer:

Resilient Distributed Dataset (RDD) - RDD stands for Resilient Distributed Dataset. It is the most basic data structure in Spark, consisting of an immutable collection of records partitioned among cluster nodes. It allows us to do fault-tolerant in-memory calculations on massive clusters.

RDD, unlike DF and DS, will not keep the schema. It merely stores data. If a user wants to apply a schema to an RDD, they must first build a case class and then apply the schema to the data.

We will use RDD for the below cases:

-When our data is unstructured, A streams of text or media streams.

-When we don’t want to implement any schema.

-When we don’t care about the column name attributes while processing or accessing.

-When we want to manipulate the data with functional programming constructs than domain specific expressions.

-When we want low-level transformation, actions and control on the dataset.

DataFrame:

-Like RDD DataFrames are immutable collection of data.

-Unlike RDD DataFrame will have schema for their data making user to easily access/process large set of data which is distributed among the nodes of cluster.

-DataFrame provides a domain specific language API to manipulate distributed data and makes Spark accessible to a wider audience, beyond specialized data engineers.

-From Spark 2.x Spark DataFrames are nothing but Dataset[Row] or alias (Untyped API)

consider DataFrame as an alias for a collection of generic objects Dataset[Row], where a Row is a generic untyped JVM object

DataSet:

Dataset, by contrast, is a collection of strongly-typed JVM objects, dictated by a case class you define in Scala or a class in Java. To implement case class on RDD and use as Dataset[T].

 Apache Tapestry Interview Questions and Answers

Ques: 5). Can you explain how you can use Apache Spark along with Hadoop?

Answer:

Apache Spark provides the benefit of being Hadoop compatible. They make a powerful tech team when they work together. Using Apache Spark and Hadoop combines the processing capability of Spark with the best capabilities of HDFS and YARN. The following are some examples of how to use Hadoop Components with Apache Spark:

Batch & Real-Time Processing – MapReduce and Spark can work together, where the former handles batch processing, and the latter handles real-time processing.

HDFS – Spark can make use of the HDFS to leverage the distributed replicated storage.

MapReduce – Apache Spark can be used in conjunction with MapReduce in a similar Hadoop cluster or independently as a processing framework.

YARN – You can run Spark applications on YARN.

 Apache NiFi Interview Questions & Answers

Ques: 6). What is the meaning of the term "spark lineage"?

Answer:

• In Spark, regardless of the actual data, all dependencies between RDDs will be logged in a graph. In Spark, this is referred to as a lineage graph.

• RDD stands for Resilient Distributed Dataset, with the term "resilient" referring to fault tolerance. We can re-compute the missing or damaged partition due to node failure using RDD Lineage Graph. When we generate new RDDs based on existing RDDs, we use lineage graph spark to handle the dependencies. Each RDD keeps a pointer to one or more parents, together with metadata describing the type of relationship it has with the parent RDD.

• RDD Lineage Graph in Spark can be obtained using the ToDebugString method.

 

Ques: 7). List the various components of the Spark Ecosystem.

Answer:

These are the five types of components in the Spark Ecosystem:

GraphX: Enables graphs and graph-parallel computation.

MLib: It is used for machine learning.

Spark Core: A powerful parallel and distributed processing platform.

Spark Streaming: Handles real-time streaming data.

Spark SQL: Combines Spark's functional programming API with relational processing.

 

Ques: 8). What is RDD in Spark? Write about it and explain it.

Answer:

Resilient Distributed Dataset (RDD) is an acronym for Resilient Distributed Dataset. RDDs are a fault-tolerant core data structure in Spark that is immutable. They've disseminated partitioned datasets among the cluster nodes.

Parallelizing and referencing a data set are the two methods for constructing RDDS. Lazy evaluation is the responsibility of the RDDS. The faster processing performance in Spark is due to the lazy evaluation of RDDs.

 

Ques: 9). In Spark, how does streaming work?

Answer:

Spark gets data in real time that is separated into batches. The Spark Engine processes these batches of data, and the final stream of results is returned back in batches. DStream, or Discretized Stream, is the most basic stream unit in Spark.

 

Ques: 10). Is it feasible to access and analyse data stored in Cassandra databases using Apache Spark?

Answer: 

Yes, Apache Spark may be used to retrieve and analyse data stored in Cassandra databases. Apache Spark can access and analyse data contained in Cassandra databases using the Spark Cassandra Connector. Spark should have a functionality that allows Spark executors to communicate with local Cassandra nodes and request just local data.

Cassandra and Apache Spark can be connected to speed up queries by lowering network traffic between Spark executors and Cassandra nodes.

 

Ques: 11). What are the advantages of using Spark SQL?

Answer:

Spark SQL carries out the following tasks:

Loads data from a variety of structured datasources, such as a relational database management system (RDBMS).

It may query data using SQL commands within the Spark programme as well as JDBC/ODBC connectors from third-party tools such as Tableau.

It can also provide SQL and Python/Scala code interaction.

 

Ques: 12). What is the purpose of Spark Executor?

Answer:

The Executors are obtained on top of worker nodes in the clusters when a SparkContext is formed. Spark Executors are in charge of performing computations and storing data on the worker node. They are also in charge of returning the results to the driver.

 

Ques: 13). What are the advantages and disadvantages of Spark?

Answer:

Advantages: Spark is known for real-time data processing, which may be employed in applications such as stock market analysis, finance, and telecommunications.

Spark's stream processing allows for real-time data analysis, which can aid in fraud detection, system alarms, and other applications.

Due to its lazy evaluation mechanism and parallel processing, Spark processes data 10 to 100 times quicker.

Disadvantages: When compared to Hadoop, Spark consumes greater storage space.

The task is distributed over numerous clusters rather than taking place on a single node.

Spark's in-memory processing might be costly when dealing with large amounts of data.

When compared to Hadoop, Spark makes better use of data.

 

Ques: 14). What are some of the drawbacks of utilising Apache Spark?

Answer:

The following are some of the drawbacks of utilising Apache Spark:

There is no file management system built-in. To take benefit of a file management system, integration with other platforms such as Hadoop is essential.

Higher latency, but lower throughput as a result

It does not support the processing of real-time data streams. In Apache Spark, live data streams are partitioned into batches, which are then processed and turned back into batches. To put it another way, Spark Streaming is more like micro-batch data processing than true real-time data processing.

There are fewer algorithms available.

Record-based window requirements are not supported by Spark streaming. It is necessary to distribute work across multiple clusters instead of running everything on a single node.

Apache Spark's in-memory ability becomes a bottleneck when used for the cost-efficient processing of big data.

 

Ques: 15). Is Apache Spark compatible with Apache Mesos?

Answer:

Yes. Spark can work on Apache Mesos-managed clusters, just as it works on YARN-managed clusters. Spark may run without a resource manager in standalone mode. If it has to execute on multiple nodes, it can use YARN or Mesos.

 

Ques: 16). What are broadcast variables, and how do they work?

Answer:

Accumulators and broadcast variables are the two types of shared variables in Spark. Instead of shipping back and forth to the driver, the broadcast variables are read-only variables cached in the Executors for local referencing. A broadcast variable preserves a read-only cached version of a variable on each computer instead of delivering a copy of the variable with tasks.

Additionally, broadcast variables are utilised to distribute a copy of a big input dataset to each node. To cut transmission costs, Apache Spark distributes broadcast variables using efficient broadcast algorithms.

There is no need to replicate variables for each task when using broadcast variables. As a result, data can be processed quickly. In contrast to RDD lookup(), broadcast variables assist in storing a lookup table inside the memory, enhancing retrieval efficiency.

 

Ques: 17). In Apache Spark, how does caching work?

Answer:

Caching RDDs in Spark speeds up processing by allowing numerous accesses to the same RDD. The function of Discretized Streams, or DStreams, in Spark streaming is to allow users to cache or retain data in memory.

The functions cache () and persist(level) are used to cache data in memory and cache memory based on the storage level specified, respectively.

The persist () without the level specifier is the same as cache, which means it caches the data in memory. The persist(level) method caches data at the provided storage level, such as on disc, on the server, or in off-heap memory.

 

Ques: 18).  What exactly is Akka? What does Spark do with it?

Answer:

Akka is a Scala and Java framework for reactive, distributed, parallel, and robust concurrent applications. Akka is the foundation for Apache Spark.

When assigning tasks to worker nodes, Spark employs Akka for job scheduling and messaging between the master and the worker node.

 

Ques: 19). What applications do you utilise Spark streaming for?

Answer:

When real-time data must be streamed into the Spark programme, this method is employed. It can be broadcast from a variety of places, such as Kafka, Flume, Amazon Kinesis, and others. For processing, the streamed data is separated into batches.

Spark streaming is used to conduct real-time sentiment analysis of customers on social media sites like as Twitter and Facebook, among others.

Live streaming data processing is critical for detecting outages, detecting fraud in financial institutions, and making stock market predictions, among other things.

 

Ques: 20). What exactly do you mean when you say "lazy evaluation"?

Answer:

The way Spark works with data is intellectual. When you ask Spark to perform a task on a dataset, it follows your instructions and records them so that it doesn't forget them - but it doesn't do anything until you tell it to. When map() is invoked on an RDD, the operation is not done immediately. Transformations aren't evaluated by Spark until you use them. This aids in the overall data processing workflow optimization.