Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas Data Structures - DataFrame

Pandas Data Structures - DataFrame

DataFrame is another core data structure in Pandas, similar to a two-dimensional table or a data table in a database.

DataFrame is a tabular data structure containing an ordered set of columns, each of which can have a different value type (numeric, string, boolean).

DataFrame has both a row index and a column index; it can be viewed as a dictionary of Series (sharing a common index).

DataFrame provides various functions for data access, filtering, slicing, merging, reshaping, aggregation, and transformation.

DataFrame is a very flexible and powerful data structure widely used for tasks such as data analysis, cleaning, transformation, and visualization.

Features of DataFrame:

The DataFrame constructor is as follows:

pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)

Parameter Description:

A Pandas DataFrame is a two-dimensional array-like structure, similar to a two-dimensional array.

Example - Creating from a list

import

pandas

as

pd

data

=

[

[

'Google'

,

10

]

,

[

'Runoob'

,

12

]

,

[

'Wiki'

,

13

]

]

Create a DataFrame

df

=

pd.

DataFrame

(

data

,

columns

=

[

'Site'

,

'Age'

]

)

Use the astype method to set the data type of each column

df

[

'Site'

]

=

df

[

'Site'

]

.

astype

(

str

)

df

[

'Age'

]

=

df

[

'Age'

]

.

astype

(

float

)

print

(

df

)

You can also create one using a dictionary:

Example - Creating from a dictionary

import

pandas

as

pd

data

=

{

'Site'

:

[

'Google'

,

'Runoob'

,

'Wiki'

]

,

'Age'

:

[

10

,

12

,

13

]

}

df

=

pd.

DataFrame

(

data

)

print

(

df

)

The output is as follows:

The following example creates from ndarrays; the ndarrays must have the same length. If an index is passed, its length should equal the length of the arrays. If no index is passed, by default the index will be range(n), where n is the array length.

For ndarrays, you can refer to:NumPy Ndarray Object

Example - Creating from ndarrays

import

numpy

as

np

import

pandas

as

pd

Create a two-dimensional ndarray containing websites and ages

ndarray_data

=

np.

array

(

[

   

[

'Google'

,

10

]

,

   

[

'Runoob'

,

12

]

,

   

[

'Wiki'

,

13

]

]

)

Create a DataFrame using the DataFrame constructor

df

=

pd.

DataFrame

(

ndarray_data

,

columns

=

[

'Site'

,

'Age'

]

)

Print the DataFrame

print

(

df

)

The output is as follows:

From the output above, we can see that the DataFrame data type is a table containing rows and columns:

You can also use a dictionary (key/value), where the key of the dictionary is the column name:

Example - Creating from a dictionary

import

pandas

as

pd

data

=

[

{

'a'

:

1

,

'b'

:

2

}

,

{

'a'

:

5

,

'b'

:

10

,

'c'

:

20

}

]

df

=

pd.

DataFrame

(

data

)

print

(

df

)

The output is:



   a   b     c

0  1   2   NaN

1  5  10  20.0

Missing corresponding data is NaN。

Pandas can use the loc attribute to return data for a specified row. If no index is set, the index of the first row is 0, the index of the second row is 1, and so on:

Example

import

pandas

as

pd

data

=

{

 

"calories"

:

[

420

,

380

,

390

]

,

 

"duration"

:

[

50

,

40

,

45

]

}

Load data into a DataFrame object

df

=

pd.

DataFrame

(

data

)

Return the first row

print

(

df.

loc

[

0

]

)

Return the second row

print

(

df.

loc

[

1

]

)

The output is as follows:



calories    420

duration     50

Name: 0, dtype: int64

calories    380

duration     40

Name: 1, dtype: int64

**Note:** The returned result is actually a Pandas Series.

You can also return multiple rows using the [[ ... ]] format, where ... is the index of each row, separated by commas:

Example

import

pandas

as

pd

data

=

{

 

"calories"

:

[

420

,

380

,

390

]

,

 

"duration"

:

[

50

,

40

,

45

]

}

Load data into a DataFrame object

df

=

pd.

DataFrame

(

data

)

Return the first and second rows

print

(

df.

loc

[

[

0

,

1

]

]

)

The output is:



   calories  duration

0       420        50

1       380        40

**Note:** The returned result is actually a Pandas DataFrame.

We can specify index values, as in the following example:

Example

import

pandas

as

pd

data

=

{

 

"calories"

:

[

420

,

380

,

390

]

,

 

"duration"

:

[

50

,

40

,

45

]

}

df

=

pd.

DataFrame

(

data

,

index

=

[

"day1"

,

"day2"

,

"day3"

]

)

print

(

df

)

The output is:



      calories  duration

day1       420        50

day2       380        40

day3       390        45

Pandas can use the loc attribute to return a row corresponding to a specified index:

Example

import

pandas

as

pd

data

=

{

 

"calories"

:

[

420

,

380

,

390

]

,

 

"duration"

:

[

50

,

40

,

45

]

}

df

=

pd.

DataFrame

(

data

,

index

=

[

"day1"

,

"day2"

,

"day3"

]

)

Specify the index

print

(

df.

loc

[

"day2"

]

)

The output is:



calories    380

duration     40

Name: day2, dtype: int64


DataFrame methods

The common operations and methods of DataFrame are shown in the table below:

Method Name Description
head(n) Return the first n rows of the DataFrame (the first 5 rows by default)
tail(n) Return the last n rows of the DataFrame (the last 5 rows by default)
info() Display brief information about the DataFrame, including column names, data types, the number of non-null values, and so on
describe() Return statistical information for the numerical columns of the DataFrame, such as mean, standard deviation, minimum, and so on
shape Return the number of rows and columns of the DataFrame (number of rows, number of columns)
columns Return all column names of the DataFrame
index Return the row index of the DataFrame
dtypes Return the numerical data type of each column
sort_values(by) Sort by a specified column
sort_index() Sort by row index
dropna() Drop rows or columns containing missing values (NaN)
fillna(value) Fill missing values with a specified value
isnull() Detect missing values, returning a boolean DataFrame
notnull() Detect non-missing values, returning a boolean DataFrame
loc[] Select data by label index
iloc[] Select data by position index
at[] Access a single element in a DataFrame (more efficient than loc[] )
iat[] Access a single element in a DataFrame (more efficient than iloc[] )
apply(func) Apply a function to a DataFrame or Series
applymap(func) Apply a function to each element of a DataFrame (DataFrame only)
groupby(by) Grouping operation, used to group by a column for summary statistics
pivot_table() Create a pivot table
merge() Merge multiple DataFrames (similar to a SQL JOIN operation)
concat() Concatenate multiple DataFrames by row or by column
to_csv() Export the DataFrame to a CSV file
to_excel() Export the DataFrame to an Excel file
to_json() Export the DataFrame to JSON format
to_sql() Export the DataFrame to a SQL database
query() Query a DataFrame using SQL-style syntax
duplicated() Return a boolean DataFrame indicating whether each row is a duplicate
drop_duplicates() Drop duplicate rows
set_index() Set the index of the DataFrame
reset_index() Reset the index of the DataFrame
transpose() Transpose the DataFrame (swap rows and columns)

Example

import

pandas

as

pd

Create DataFrame

data

=

{

   

'Name'

:

[

'Alice'

,

'Bob'

,

'Charlie'

,

'David'

]

,

   

'Age'

:

[

25

,

30

,

35

,

40

]

,

   

'City'

:

[

'New York'

,

'Los Angeles'

,

'Chicago'

,

'Houston'

]

}

df

=

pd.

DataFrame

(

data

)

View the first two rows of data

print

(

df.

head

(

2

)

)

View basic information about the DataFrame

print

(

df.

info

(

)

)

Get descriptive statistics

print

(

df.

describe

(

)

)

Sort by age

df_sorted

=

df.

sort_values

(

by

=

'Age'

,

ascending

=

False

)

print

(

df_sorted

)

Select specified columns

print

(

df

[

[

'Name'

,

'Age'

]

]

)

Select rows by index

print

(

df.

iloc

[

1

:

3

]

)

 

Select the second to third rows (by position)

Select rows by label

print

(

df.

loc

[

1

:

2

]

)

 

Select the second to third rows (by label)

Compute grouped statistics (group by city and calculate the average age)

print

(

df.

groupby

(

'City'

)

[

'Age'

]

.

mean

(

)

)

Handle missing values (fill missing values)

df

[

'Age'

]

=

df

[

'Age'

]

.

fillna

(

30

)

Export to a CSV file

df.

to_csv

(

'output.csv'

,

index

=

False

)

The output is:



# View the first two lines of data

     Name  Age         City

0   Alice   25     New York

1     Bob   30  Los Angeles



# View basic information of the DataFrame



RangeIndex: 4 entries, 0 to 3

Data columns (total 3 columns):

 #   Column  Non-Null Count  Dtype  

---  ------  --------------  -----  

 0   Name    4 non-null      object 

 1   Age     4 non-null      int64  

 2   City    4 non-null      object 

dtypes: int64(1), object(2)

memory usage: 148.0+ bytes



# Get descriptive statistics

             Age

count   4.000000

mean   32.500000

std     6.454972

min    25.000000

25%    27.500000

50%    32.500000

75%    37.500000

max    40.000000



# Sort by age

      Name  Age         City

3    David   40     Houston

2  Charlie   35      Chicago

1      Bob   30  Los Angeles

0    Alice   25     New York



# Select rows by tag

      Name  Age         City

1     Bob   30  Los Angeles

2  Charlie   35      Chicago



# Calculate grouped statistics (group by city, calculate average age)

City

Chicago        35.0

Houston        40.0

Los Angeles    30.0

New York       25.0

Name: Age, dtype: float64


More information about DataFrame

Create DataFrame

**Creating from a dictionary:** The keys of the dictionary become column names, and the values become column data.

Example

import

pandas

as

pd

Create a DataFrame from a dictionary

df

=

pd.

DataFrame

(

{

'Column1'

:

[

1

,

2

,

3

]

,

'Column2'

:

[

4

,

5

,

6

]

}

)

**Creating from a list of lists:** The outer list represents rows, and the inner list represents columns.

Create a DataFrame from a list of lists

Example

df

=

pd.

DataFrame

(

[

[

1

,

2

,

3

]

,

[

4

,

5

,

6

]

,

[

7

,

8

,

9

]

]

,

                  columns

=

[

'Column1'

,

'Column2'

,

'Column3'

]

)

**Creating from a NumPy array:** Provide a two-dimensional NumPy array.

Example

import

numpy

as

np

Create a DataFrame from a NumPy array

df

=

pd.

DataFrame

(

np.

array

(

[

[

1

,

2

,

3

]

,

[

4

,

5

,

6

]

,

[

7

,

8

,

9

]

]

)

)

**Creating a DataFrame from a Series:** Create via pd.Series().

Example

Create a DataFrame from a Series

s1

=

pd.

Series

(

[

'Alice'

,

'Bob'

,

'Charlie'

]

)

s2

=

pd.

Series

(

[

25

,

30

,

35

]

)

s3

=

pd.

Series

(

[

'New York'

,

'Los Angeles'

,

'Chicago'

]

)

df

=

pd.

DataFrame

(

{

'Name'

: s1

,

'Age'

: s2

,

'City'

: s3

}

)

Attributes and methods of DataFrame

A DataFrame object has many attributes and methods for data manipulation, indexing, and processing, such as shape, columns, index, head(), tail(), info(), describe(), mean(), sum(), and so on.

Example

Attributes and methods of DataFrame

print

(

df.

shape

)

   

Shape

print

(

df.

columns

)

 

Column Name

print

(

df.

index

)

   

Index

print

(

df.

head

(

)

)

   

The first few rows of data, the first 5 rows by default

print

(

df.

tail

(

)

)

   

The last few rows of data, the last 5 rows by default

print

(

df.

info

(

)

)

   

Data information

print

(

df.

describe

(

)

)

Descriptive statistics

print

(

df.

mean

(

)

)

   

Compute the mean

print

(

df.

sum

(

)

)

   

Sum

Accessing DataFrame elements

**Accessing columns:** Use the column name as an attribute or access via .loc[] and .iloc[]; you can also use label or position indexing.

Example

Access by column name

print

(

df

[

'Column1'

]

)

Access by attribute

print

(

df.

Name

)

   

   

Access via .loc[]

print

(

df.

loc

[

:

,

'Column1'

]

)

Access via .iloc[]

print

(

df.

iloc

[

:

,

0

]

)

 

Assume 'Column1' is the first column

Access a single element

print

(

df

[

'Name'

]

[

0

]

)

**Accessing rows:** Use the row's label and .loc[] for access.

Example

Access by row label

print

(

df.

loc

[

0

,

'Column1'

]

)

Modifying DataFrame

**Modifying column data:** Assign a value directly to the column.

df['Column1'] = [10, 11, 12]

**Adding a new column:** Assign a value to the new column.

df['NewColumn'] = [100, 200, 300]

**Adding a new row:** Use the loc, append, or concat method.

Example

Use loc to add a new row for a specific index

df.

loc

[

3

]

=

[

13

,

14

,

15

,

16

]

Use append to add a new row to the end

new_row

=

{

'Column1'

:

13

,

'Column2'

:

14

,

'NewColumn'

:

16

}

df

=

df.

append

(

new_row

,

ignore_index

=

True

)

**Note:**append() The method has been marked as deprecated in pandas version 1.4.0 and will be removed in a future version. The official recommendation is to use concat() as an alternative for merging data.

The concat() method is used to merge two or more DataFrames. When you want to add a row to another DataFrame, you can treat the new row as a new DataFrame and then use concat():

Example

Add a new row using concat

new_row

=

pd.

DataFrame

(

[

[

4

,

7

]

]

,

columns

=

[

'A'

,

'B'

]

)

 

Create a DataFrame containing only the new row

df

=

pd.

concat

(

[

df

,

new_row

]

,

ignore_index

=

True

)

 

Add the new row to the original DataFrame

print

(

df

)

Deleting DataFrame elements

**Dropping columns:** Use the drop method.

df_dropped = df.drop('Column1', axis=1)

**Dropping rows:** Also use the drop method.

df_dropped = df.drop(0)  # 删除索引为 0 的行

Statistical analysis of DataFrame

**Descriptive statistics:** Use .describe() to view a statistical summary of the numerical columns.

df.describe()

**Calculating statistics:** Use aggregate functions such as .sum(), .mean(), .max(), and so on.

df['Column1'].sum()

df.mean()

Index operations on DataFrame

**Resetting the index:** Use .reset_index().

df_reset = df.reset_index(drop=True)

**Setting the index:** Use .set_index().

df_set = df.set_index('Column1')

Boolean indexing of DataFrame

Using boolean expressions: Filter the DataFrame based on conditions.

df[df['Column1'] > 2]

Data types of DataFrame

View data types: Use the dtypes attribute.

df.dtypes

**Converting data types:** Use the astype method.

df['Column1'] = df['Column1'].astype('float64')

Merging and splitting DataFrame

**Merging:** Use the concat or merge method.

# 纵向合并

pd.concat([df1, df2], ignore_index=True)



# Horizontal merge

pd.merge(df1, df2, on='Column1')

**Splitting:** Use pivot, melt, or custom functions.



# Convert long format to wide format

df_pivot = df.pivot(index='Column1', columns='Column2', values='Column3')



# Wide to long format

df_melt = df.melt(id_vars='Column1', value_vars=['Column2', 'Column3'])

Indexing and slicing

DataFrame supports indexing and slicing operations on rows and columns.

Example

Indexing and slicing

print

(

df

[

[

'Name'

,

'Age'

]

]

)

 

Extract multiple columns

print

(

df

[

1

:

3

]

)

             

Slice rows

print

(

df.

loc

[

:

,

'Name'

]

)

   

Extract a single column

print

(

df.

loc

[

1

:

2

,

[

'Name'

,

'Age'

]

]

)

 

Extract specified rows and columns by label indexing

print

(

df.

iloc

[

:

,

1

:

]

)

       

Extract specified columns by position indexing

Notes