Limited rows selection with given column in Pandas | Python (original) (raw)
Last Updated : 24 Oct, 2019
Methods in Pandas like iloc[]
, iat[]
are generally used to select the data from a given dataframe. In this article, we will learn how to select the limited rows with given columns with the help of these methods.
Example 1: Select two columns
import
pandas as pd
data
=
{
'Name'
:[
'Jai'
,
'Princi'
,
'Gaurav'
,
'Anuj'
],
`` 'Age'
:[
27
,
24
,
22
,
32
],
`` 'Address'
:[
'Delhi'
,
'Kanpur'
,
'Allahabad'
,
'Kannauj'
],
`` 'Qualification'
:[
'Msc'
,
'MA'
,
'MCA'
,
'Phd'
]}
df
=
pd.DataFrame(data)
print
(df.loc[
1
:
3
, [
'Name'
,
'Qualification'
]])
Output:
Name Qualification
1 Princi MA 2 Gaurav MCA 3 Anuj Phd
Example 2: First filtering rows and selecting columns by label format and then Select all columns.
import
pandas as pd
data
=
{
'Name'
:[
'Jai'
,
'Princi'
,
'Gaurav'
,
'Anuj'
],
`` 'Age'
:[
27
,
24
,
22
,
32
],
`` 'Address'
:[
'Delhi'
,
'Kanpur'
,
'Allahabad'
,
'Kannauj'
],
`` 'Qualification'
:[
'Msc'
,
'MA'
,
'MCA'
,
'Phd'
]
`` }
df
=
pd.DataFrame(data)
print
(df.loc[
0
, :] )
Output:
Address Delhi Age 27 Name Jai Qualification Msc Name: 0, dtype: object
Example 3: Select all or some columns, one to another using .iloc.
import
pandas as pd
data
=
{
'Name'
:[
'Jai'
,
'Princi'
,
'Gaurav'
,
'Anuj'
],
`` 'Age'
:[
27
,
24
,
22
,
32
],
`` 'Address'
:[
'Delhi'
,
'Kanpur'
,
'Allahabad'
,
'Kannauj'
],
`` 'Qualification'
:[
'Msc'
,
'MA'
,
'MCA'
,
'Phd'
]}
df
=
pd.DataFrame(data)
print
(df.iloc [
0
:
2
,
1
:
3
] )
Output:
Age Name 0 27 Jai 1 24 Princi
Similar Reads
- Pandas Exercises and Programs Pandas is an open-source Python Library that is made mainly for working with relational or labelled data both easily and intuitively. This Python library is built on top of the NumPy library, providing various operations and data structures for manipulating numerical data and time series. Pandas is 6 min read
- Different ways to create Pandas Dataframe It is the most commonly used Pandas object. The pd.DataFrame() function is used to create a DataFrame in Pandas. There are several ways to create a Pandas Dataframe in Python. Example: Creating a DataFrame from a Dictionary [GFGTABS] Python import pandas as pd # initialize data of lists. data = { 7 min read