ななぶろ

-お役立ち情報を気楽に紹介するブログ-

PythonPandasプログラミング練習問題10選:データ分析の基礎を固める

www.amazon.co.jp

Python Pandas プログラミング練習問題 10 選:データ分析の基礎を固める

Python のデータ分析ライブラリとして広く利用されている Pandas は、データの操作・加工・分析を行う上で不可欠なツールです。本記事では、Pandas を効果的に習得するための練習問題を 10 選紹介します。初心者の方でも理解しやすいように、各問題に対して丁寧な解説と具体的なコード例を提示し、必要に応じて参照先も記載します。

Pandas とは?

Pandas は、Python でデータ分析を行うためのライブラリです。NumPy を基盤としており、データの操作や分析を効率的に行うための様々な機能を提供しています。主な特徴としては以下の点が挙げられます。

  • DataFrame: 表形式のデータを扱うための主要なデータ構造。Excel のシートや SQL のテーブルのように、行と列で構成されたデータセットを表現できます。
  • Series: 1 次元配列のようなデータ構造。DataFrame の各列は Series として扱われます。
  • データの読み込み・書き出し: CSV, Excel, SQL データベースなど、様々な形式のデータを簡単に読み込んだり、書き出したりすることができます。
  • データの操作: データのフィルタリング、ソート、結合、グループ化など、様々な操作を効率的に行うことができます。
  • 欠損値処理: データに含まれる欠損値を適切に処理するための機能が提供されています。
  • データ集計・分析: 統計的な計算や可視化のための機能も備わっています。

Pandas を習得することで、データの前処理から分析、結果の可視化まで、一連のデータ分析プロセスを効率的に行うことができます。

What is Pandas?

Pandas is a library in Python used for data analysis. Built on top of NumPy, it provides various functions to efficiently manipulate and analyze data. Key features include:

  • DataFrame: A primary data structure for handling tabular data, similar to an Excel sheet or SQL table, composed of rows and columns.
  • Series: A one-dimensional array-like data structure; each column in a DataFrame is treated as a Series.
  • Data Input/Output: Easily reads and writes data in various formats like CSV, Excel, and SQL databases.
  • Data Manipulation: Efficiently performs operations such as filtering, sorting, merging, and grouping of data.
  • Missing Value Handling: Provides functions to handle missing values (NaN) appropriately.
  • Data Aggregation & Analysis: Includes functionalities for statistical calculations and visualization.

By mastering Pandas, you can efficiently perform the entire data analysis process, from preprocessing to analysis and result visualization.

練習問題と解説

それでは、Pandas の基礎を習得するための練習問題を 10 選紹介します。各問題に対して、解答例だけでなく、問題に取り組む上でのポイントや注意点も解説します。

1. CSV ファイルの読み込みと表示

  • 問題: data.csv という名前の CSV ファイルを Pandas DataFrame に読み込み、最初の 5 行を表示してください。
  • 解答例:
import pandas as pd

# CSV ファイルを読み込む
df = pd.read_csv('data.csv')

# 最初の 5 行を表示する
print(df.head())
  • 解説: pd.read_csv() 関数は、CSV ファイルを DataFrame に変換します。df.head() メソッドは、DataFrame の最初の数行 (デフォルトでは 5 行) を表示します。これはデータの概要を素早く確認するために非常に役立ちます。
  • ポイント: CSV ファイルのパスが正しいことを確認してください。ファイル名やディレクトリ構造が間違っているとエラーが発生します。相対パスまたは絶対パスを使用できます。また、CSV ファイルのエンコーディング (UTF-8, Shift_JIS など) が Python のデフォルトと異なる場合は、encoding 引数を使用して指定する必要があります。
  • 参照先: Pandas read_csv

What is Problem 1?

  • Problem: Read a CSV file named data.csv into a Pandas DataFrame and display the first 5 rows.
  • Solution:
import pandas as pd

# Read the CSV file
df = pd.read_csv('data.csv')

# Display the first 5 rows
print(df.head())
  • Explanation: The pd.read_csv() function converts a CSV file into a DataFrame. The df.head() method displays the first few rows (default is 5) of the DataFrame, allowing for a quick overview of the data.
  • Key Points: Ensure the path to your CSV file is correct. Use either a relative or absolute path. If the CSV file uses an encoding different from Python's default (e.g., UTF-8, Shift_JIS), specify it using the encoding argument in pd.read_csv().
  • Reference: Pandas read_csv

2. DataFrame の情報表示

  • 問題: 読み込んだ DataFrame の情報を表示してください (列名、データ型、欠損値の数など)。
  • 解答例:
import pandas as pd

df = pd.read_csv('data.csv')

# DataFrame の情報を表示する
print(df.info())
  • 解説: df.info() メソッドは、DataFrame の概要を表示します。列名、データ型 (int64, float64, object など)、非 null 値の数などが確認できます。これはデータの構造を理解し、適切な分析手法を選択するために不可欠です。
  • ポイント: データ型の確認は、データの分析を行う上で重要です。数値データが文字列型で読み込まれている場合など、適切なデータ型に変換する必要がある場合があります。object 型は通常、文字列や混合型を表します。
  • 参照先: Pandas info

What is Problem 2?

  • Problem: Display information about the DataFrame you read in, including column names, data types, and the number of missing values.
  • Solution:
import pandas as pd

df = pd.read_csv('data.csv')

# Display DataFrame information
print(df.info())
  • Explanation: The df.info() method displays an overview of the DataFrame, including column names, data types (e.g., int64, float64, object), and the number of non-null values. This is crucial for understanding the structure of your data and selecting appropriate analysis methods.
  • Key Points: Pay close attention to data types. If numerical data is read as a string type, you'll need to convert it to the correct type. The object dtype typically represents strings or mixed types.
  • Reference: Pandas info

3. 列の選択と抽出

  • 問題: DataFrame から特定の列 (例: 'Name', 'Age') を選択し、新しい DataFrame として抽出してください。
  • 解答例:
import pandas as pd

df = pd.read_csv('data.csv')

# 特定の列を選択する
new_df = df[['Name', 'Age']]

# 新しい DataFrame を表示する
print(new_df)
  • 解説: df[[...]] のように、DataFrame 内の列名をリストで指定することで、複数の列を選択できます。これにより、特定の列のみを抽出し、分析に集中することができます。
  • ポイント: 列名にスペースが含まれている場合は、シングルクォートまたはダブルクォートで囲んでください。また、単一の列を選択する場合は df['ColumnName'] のように記述することも可能です。
  • 参照先: Pandas bracket notation

What is Problem 3?

  • Problem: Select specific columns (e.g., 'Name', 'Age') from the DataFrame and extract them into a new DataFrame.
  • Solution:
import pandas as pd

df = pd.read_csv('data.csv')

# Select specific columns
new_df = df[['Name', 'Age']]

# Display the new DataFrame
print(new_df)
  • Explanation: You can select multiple columns by providing a list of column names within double square brackets df[[...]]. This allows you to extract only the relevant columns for your analysis.
  • Key Points: If a column name contains spaces, enclose it in single or double quotes. To select a single column, use df['ColumnName'].
  • Reference: Pandas bracket notation

4. 行の選択と抽出 (条件指定)

  • 問題: DataFrame から特定の条件を満たす行を抽出してください (例: 'Age' が 30 歳以上の行)。
  • 解答例:
import pandas as pd

df = pd.read_csv('data.csv')

# 条件を満たす行を選択する
filtered_df = df[df['Age'] >= 30]

# 抽出された DataFrame を表示する
print(filtered_df)
  • 解説: df[...] のように、条件式を記述することで、DataFrame から特定の条件を満たす行を抽出できます。これにより、特定の属性を持つデータのみに焦点を当てることができます。
  • ポイント: 条件式は、Python の比較演算子 (>=, <=, ==, != など) を使用して記述します。複数の条件を組み合わせる場合は、論理演算子 (&: AND, |: OR, ~: NOT) を使用できます。
  • 参照先: Pandas boolean indexing

What is Problem 4?

  • Problem: Extract rows from the DataFrame that meet a specific condition (e.g., rows where 'Age' is greater than or equal to 30).
  • Solution:
import pandas as pd

df = pd.read_csv('data.csv')

# Select rows based on a condition
filtered_df = df[df['Age'] >= 30]

# Display the filtered DataFrame
print(filtered_df)
  • Explanation: You can extract specific rows by using a boolean expression within square brackets df[...]. This allows you to focus your analysis on data with particular attributes.
  • Key Points: Use Python's comparison operators (>=, <=, ==, !=, etc.) in the condition. Combine multiple conditions using logical operators (& for AND, | for OR, ~ for NOT).
  • Reference: Pandas boolean indexing

5. 新しい列の作成

  • 問題: DataFrame に新しい列を作成し、既存の列に基づいて計算結果を格納してください (例: 'Age' 列に 10 を加算した新しい列 'Age_Plus_10' を作成)。
  • 解答例:
import pandas as pd

df = pd.read_csv('data.csv')

# 新しい列を作成する
df['Age_Plus_10'] = df['Age'] + 10

# DataFrame を表示する
print(df)
  • 解説: df['新しい列名'] = ... のように、DataFrame に新しい列名を指定し、その列に値を代入することで、新しい列を作成できます。これにより、既存のデータから派生した情報を追加することができます。
  • ポイント: 新しい列のデータ型は、計算結果に基づいて自動的に決定されます。必要に応じて、astype() メソッドを使用して明示的にデータ型を指定することもできます。例えば、df['Age_Plus_10'] = df['Age'].astype(float) + 10 のように記述することで、確実に浮動小数点数として新しい列を作成できます。
  • 参照先: Pandas adding and deleting columns

What is Problem 5?

  • Problem: Create a new column in the DataFrame based on existing columns (e.g., create a new column 'Age_Plus_10' by adding 10 to the 'Age' column).
  • Solution:
import pandas as pd

df = pd.read_csv('data.csv')

# Create a new column
df['Age_Plus_10'] = df['Age'] + 10

# Display the DataFrame
print(df)
  • Explanation: You can create a new column by assigning a value to it using df['new_column_name'] = .... This allows you to add derived information based on existing data.
  • Key Points: The data type of the new column is automatically determined based on the calculation result. You can explicitly specify the data type using the astype() method, for example: df['Age_Plus_10'] = df['Age'].astype(float) + 10 to ensure it's a float.
  • Reference: Pandas adding and deleting columns

6. 欠損値の処理

  • 問題: DataFrame に欠損値 (NaN) が含まれている場合、その欠損値を特定し、適切な方法で処理してください (例: 欠損値を平均値で補完)。
  • 解答例:
import pandas as pd

df = pd.read_csv('data.csv')

# 欠損値の数を表示する
print(df.isnull().sum())

# 'Age' 列の欠損値を平均値で補完する
df['Age'] = df['Age'].fillna(df['Age'].mean())

# DataFrame を表示する
print(df)
  • 解説: df.isnull() は、DataFrame の各要素が欠損値かどうかを示すブール値の DataFrame を返します。df.isnull().sum() は、各列の欠損値の数を表示します。fillna() メソッドは、欠損値を指定された値で補完します。平均値での補完以外にも、中央値、最頻値、定数などで補完することも可能です。
  • ポイント: 欠損値の処理方法は、データの性質や分析の目的に応じて適切に選択する必要があります。単純な平均値補完は、データ分布が正規分布に近い場合に有効ですが、外れ値の影響を受けやすいという欠点があります。
  • 参照先: Pandas handling missing data

What is Problem 6?

  • Problem: Identify and handle missing values (NaN) in the DataFrame (e.g., fill missing values in the 'Age' column with the mean).
  • Solution:
import pandas as pd

df = pd.read_csv('data.csv')

# Display the number of missing values per column
print(df.isnull().sum())

# Fill missing values in the 'Age' column with the mean
df['Age'] = df['Age'].fillna(df['Age'].mean())

# Display the DataFrame
print(df)
  • Explanation: df.isnull() returns a boolean DataFrame indicating whether each element is a missing value. df.isnull().sum() displays the number of missing values per column. The fillna() method fills missing values with a specified value.
  • Key Points: Choose an appropriate method for handling missing values based on the data's characteristics and your analysis goals. Mean imputation is effective when the data distribution is close to normal, but it can be influenced by outliers. Consider using median, mode, or constant values as alternatives.
  • Reference: Pandas handling missing data

7. グループ化と集計

  • 問題: DataFrame を特定の列 (例: 'City') でグループ化し、各グループに対して統計的な集計 (平均、合計、最大値など) を行い、結果を表示してください。
  • 解答例:
import pandas as pd

df = pd.read_csv('data.csv')

# 'City' 列でグループ化し、'Age' 列の平均値を計算する
grouped_df = df.groupby('City')['Age'].mean()

# 結果を表示する
print(grouped_df)
  • 解説: df.groupby() メソッドは、DataFrame を指定された列でグループ化します。['Age'].mean() は、各グループの 'Age' 列の平均値を計算します。集計関数には、sum(), max(), min(), std() など様々なものが利用可能です。
  • ポイント: グループ化と集計を組み合わせることで、データの傾向やパターンを把握することができます。例えば、都市ごとの年齢層の分布を分析することで、各都市の人口構成に関する洞察を得ることができます。
  • 参照先: Pandas groupby

What is Problem 7?

  • Problem: Group the DataFrame by a specific column (e.g., 'City') and perform statistical aggregations (mean, sum, max, etc.) on each group, then display the results.
  • Solution:
import pandas as pd

df = pd.read_csv('data.csv')

# Group by 'City' and calculate the mean of the 'Age' column for each group
grouped_df = df.groupby('City')['Age'].mean()

# Display the results
print(grouped_df)
  • Explanation: The df.groupby() method groups the DataFrame by a specified column. ['Age'].mean() calculates the mean of the 'Age' column for each group. Various aggregation functions are available, such as sum(), max(), min(), and std().
  • Key Points: Combining grouping and aggregation allows you to understand data trends and patterns. For example, analyzing age distributions by city can provide insights into the demographic composition of each city.
  • Reference: Pandas groupby

8. データのソート

  • 問題: DataFrame を特定の列 (例: 'Age') でソートしてください (昇順または降順)。
  • 解答例:
import pandas as pd

df = pd.read_csv('data.csv')

# 'Age' 列で昇順にソートする
sorted_df = df.sort_values(by='Age', ascending=True)

# ソートされた DataFrame を表示する
print(sorted_df)
  • 解説: df.sort_values() メソッドは、DataFrame を指定された列でソートします。ascending=True は昇順 (小さい順)、ascending=False は降順 (大きい順) を意味します。複数の列でソートすることも可能です。
  • ポイント: ソートは、データの可視化や分析を行う上で重要な前処理ステップです。例えば、年齢の高い順にデータを並べ替えることで、高齢者の傾向を把握しやすくなります。
  • 参照先: Pandas sort_values

What is Problem 8?

  • Problem: Sort the DataFrame by a specific column (e.g., 'Age') in ascending or descending order.
  • Solution:
import pandas as pd

df = pd.read_csv('data.csv')

# Sort by 'Age' in ascending order
sorted_df = df.sort_values(by='Age', ascending=True)

# Display the sorted DataFrame
print(sorted_df)
  • Explanation: The df.sort_values() method sorts the DataFrame by a specified column. ascending=True indicates ascending order (smallest to largest), while ascending=False indicates descending order (largest to smallest). You can sort by multiple columns as well.
  • Key Points: Sorting is an important preprocessing step for data visualization and analysis. For example, sorting by age in descending order can make it easier to identify trends among older individuals.
  • Reference: Pandas sort_values

9. データの結合 (merge)

  • 問題: 2 つの DataFrame を特定の列 (例: 'ID') で結合してください。
  • 解答例:
import pandas as pd

# DataFrame 1
df1 = pd.DataFrame({'ID': [1, 2, 3], 'Name': ['Alice', 'Bob', 'Charlie']})

# DataFrame 2
df2 = pd.DataFrame({'ID': [1, 2, 4], 'Age': [25, 30, 28]})

# 'ID' 列で結合する (inner join)
merged_df = pd.merge(df1, df2, on='ID', how='inner')

# 結合された DataFrame を表示する
print(merged_df)
  • 解説: pd.merge() 関数は、2 つの DataFrame を指定された列で結合します。how 引数には、結合の種類 (inner, outer, left, right) を指定できます。Inner join は、両方の DataFrame に共通するキーを持つ行のみを保持します。
  • ポイント: データの結合は、複数のデータソースから情報を統合する際に不可欠な操作です。結合の種類によって結果が異なるため、分析の目的に応じて適切な種類を選択する必要があります。
  • 参照先: Pandas merge

What is Problem 9?

  • Problem: Merge two DataFrames based on a specific column (e.g., 'ID').
  • Solution:
import pandas as pd

# DataFrame 1
df1 = pd.DataFrame({'ID': [1, 2, 3], 'Name': ['Alice', 'Bob', 'Charlie']})

# DataFrame 2
df2 = pd.DataFrame({'ID': [1, 2, 4], 'Age': [25, 30, 28]})

# Merge based on the 'ID' column (inner join)
merged_df = pd.merge(df1, df2, on='ID', how='inner')

# Display the merged DataFrame
print(merged_df)
  • Explanation: The pd.merge() function merges two DataFrames based on a specified column. The how argument specifies the type of join (inner, outer, left, right). An inner join keeps only rows that have matching keys in both DataFrames.
  • Key Points: Merging data is essential when integrating information from multiple data sources. The choice of join type affects the result, so select the appropriate type based on your analysis goals.
  • Reference: Pandas merge

10. データのエクスポート

  • 問題: DataFrame を CSV ファイルにエクスポートしてください。
  • 解答例:
import pandas as pd

df = pd.read_csv('data.csv')

# DataFrame を CSV ファイルにエクスポートする
df.to_csv('output.csv', index=False)
  • 解説: df.to_csv() メソッドは、DataFrame を CSV ファイルに書き出します。index=False は、インデックスをファイルに含めないように指定します。
  • ポイント: データのエクスポートは、分析結果を他のシステムやアプリケーションと共有する際に必要となる操作です。エクスポート先のファイルパスが正しいことを確認してください。
  • 参照先: Pandas to_csv

まとめ

本記事では、Pandas の基礎を習得するための練習問題を 10 選紹介しました。これらの問題に取り組むことで、データの読み込み・加工・分析に必要な Pandas の基本的な操作を習得することができます。

Pandas は非常に強力なツールであり、データ分析の効率を大幅に向上させることができます。ぜひ、本記事で紹介した練習問題を参考に、Pandas を効果的に活用してください。さらに深く学びたい場合は、Pandas の公式ドキュメントを参照することをお勧めします。 Pandas 公式ドキュメント

これらの練習問題はあくまで出発点です。より複雑なデータ分析課題に取り組むことで、Pandas の理解を深めることができます。頑張ってください!

補足:Pandas をさらに深く学ぶために

上記の問題を通して Pandas の基本的な操作を学んだ後、さらに以下のトピックについて学習することで、Pandas の活用範囲を広げることができます。

  • データ型の変換: astype() メソッドを使用して、列のデータ型を柔軟に変換できます。
  • インデックスの設定と操作: DataFrame のインデックスをカスタマイズしたり、階層的なインデックスを作成したりすることができます。
  • 多次元インデックス (MultiIndex): 複数の列を組み合わせてインデックスを作成することで、より複雑なデータの構造を表現できます。
  • ピボットテーブル: pivot_table() 関数を使用して、データを集計し、表形式で表示することができます。
  • データフレームの結合方法の詳細: merge() 関数の how 引数には、inner, outer, left, right 以外にも様々なオプションがあります。それぞれの違いを理解することで、より適切な結合を行うことができます。
  • 文字列操作: Pandas は、文字列データの操作のための豊富な機能を提供しています。str アクセサを使用して、文字列の抽出、置換、分割などの操作を行うことができます。
  • 日付と時刻の処理: to_datetime() 関数を使用して、文字列を日付型に変換したり、日付や時刻に関する様々な計算を行ったりすることができます。
  • カテゴリデータ: astype('category') を使用して、頻繁に出現する文字列データをカテゴリデータとして扱うことで、メモリ使用量を削減し、パフォーマンスを向上させることができます。

これらのトピックについて学習することで、Pandas をより深く理解し、より高度なデータ分析を行うことができるようになります。

English Translation:

10 Python Pandas Programming Practice Problems: Solidify the Fundamentals of Data Analysis

Pandas, a widely used data analysis library in Python, is an essential tool for manipulating, processing, and analyzing data. This article introduces 10 practice problems to effectively master Pandas. We will provide detailed explanations and concrete code examples for each problem, ensuring they are accessible even to beginners. We'll also include references where applicable.

What is Pandas?

Pandas is a Python library designed for data analysis. Built upon NumPy, it provides various functions for efficient data manipulation and analysis. Key features include:

  • DataFrame: A primary data structure for handling tabular data. It represents datasets composed of rows and columns, similar to an Excel sheet or SQL table.
  • Series: A one-dimensional array-like data structure. Each column in a DataFrame is treated as a Series.
  • Data Input/Output: Easily read data from and write data to various formats like CSV, Excel, and SQL databases.
  • Data Manipulation: Efficiently perform operations such as filtering, sorting, merging, and grouping of data.
  • Missing Value Handling: Provides functions for appropriately handling missing values within the data.
  • Data Aggregation & Analysis: Includes functionalities for statistical calculations and visualization.

By mastering Pandas, you can efficiently handle the entire data analysis process, from preprocessing to analysis and result visualization.

Practice Problems and Explanations

Let's introduce 10 practice problems designed to help you master Pandas fundamentals. For each problem, we’ll provide example solutions, along with key points and considerations for tackling the challenge.

1. Reading a CSV File and Displaying It

  • Problem: Read a CSV file named data.csv into a Pandas DataFrame and display the first 5 rows.
  • Solution:
import pandas as pd

# Read the CSV file into a DataFrame
df = pd.read_csv('data.csv')

# Display the first 5 rows
print(df.head())
  • Explanation: The pd.read_csv() function converts a CSV file into a DataFrame. The df.head() method displays the first few rows (default is 5) of the DataFrame.
  • Key Point: Verify that the path to your CSV file is correct. Errors will occur if the filename or directory structure is incorrect.
  • Reference: Pandas read_csv

2. Displaying DataFrame Information

  • Problem: Display information about the loaded DataFrame (column names, data types, number of missing values).
  • Solution:
import pandas as pd

df = pd.read_csv('data.csv')

# Display DataFrame information
print(df.info())
  • Explanation: The df.info() method displays an overview of the DataFrame, including column names, data types, and the number of non-null values.
  • Key Point: Checking data types is crucial for effective data analysis. You might need to convert data to appropriate types if numerical data is read as strings, for example.

3. Selecting and Extracting Columns

  • Problem: Select specific columns (e.g., 'Name', 'Age') from the DataFrame and extract them into a new DataFrame.
  • Solution:
import pandas as pd

df = pd.read_csv('data.csv')

# Select specific columns
new_df = df[['Name', 'Age']]

# Display the new DataFrame
print(new_df)
  • Explanation: You can select multiple columns by specifying a list of column names within square brackets: df[[...]].
  • Key Point: If column names contain spaces, enclose them in single or double quotes.

4. Selecting and Extracting Rows (Condition-Based)

  • Problem: Extract rows from the DataFrame that meet a specific condition (e.g., rows where 'Age' is greater than or equal to 30).
  • Solution:
import pandas as pd

df = pd.read_csv('data.csv')

# Select rows based on a condition
filtered_df = df[df['Age'] >= 30]

# Display the filtered DataFrame
print(filtered_df)
  • Explanation: You can extract rows that meet a specific condition by using a boolean expression within square brackets: df[...].
  • Key Point: Use Python comparison operators (>=, <=, ==, !=, etc.) to define your conditions.

5. Creating New Columns

  • Problem: Create a new column in the DataFrame and store calculated results based on existing columns (e.g., create a new column 'Age_Plus_10' by adding 10 to the 'Age' column).
  • Solution:
import pandas as pd

df = pd.read_csv('data.csv')

# Create a new column
df['Age_Plus_10'] = df['Age'] + 10

# Display the DataFrame
print(df)
  • Explanation: You can create a new column by assigning values to it using df['new_column_name'] = ....
  • Key Point: The data type of the new column will be automatically determined based on the calculation results. You can explicitly specify the data type using the astype() method if needed.

6. Handling Missing Values

  • Problem: If the DataFrame contains missing values (NaN), identify them and handle them appropriately (e.g., fill missing values in the 'Age' column with the mean).
  • Solution:
import pandas as pd

df = pd.read_csv('data.csv')

# Display the number of missing values per column
print(df.isnull().sum())

# Fill missing values in the 'Age' column with the mean
df['Age'] = df['Age'].fillna(df['Age'].mean())

# Display the DataFrame
print(df)
  • Explanation: df.isnull() returns a boolean DataFrame indicating whether each element is a missing value. df.isnull().sum() displays the number of missing values per column. The fillna() method fills missing values with a specified value.
  • Key Point: Choose an appropriate method for handling missing values based on the nature of your data and the goals of your analysis.

7. Grouping and Aggregation

  • Problem: Group the DataFrame by a specific column (e.g., 'City') and perform statistical aggregations (mean, sum, maximum, etc.) on another column ('Age') for each group, then display the results.
  • Solution:
import pandas as pd

df = pd.read_csv('data.csv')

# Group by 'City' and calculate the mean of 'Age' for each group
grouped_df = df.groupby('City')['Age'].mean()

# Display the results
print(grouped_df)
  • Explanation: The df.groupby() method groups the DataFrame based on a specified column. ['Age'].mean() calculates the mean of the 'Age' column for each group.
  • Key Point: Combining grouping and aggregation allows you to understand trends and patterns in your data.

8. Sorting Data

  • Problem: Sort the DataFrame by a specific column (e.g., 'Age') in ascending or descending order.
  • Solution:
import pandas as pd

df = pd.read_csv('data.csv')

# Sort by 'Age' in ascending order
sorted_df = df.sort_values(by='Age', ascending=True)

# Display the sorted DataFrame
print(sorted_df)
  • Explanation: The df.sort_values() method sorts the DataFrame based on a specified column. ascending=True indicates ascending order (smallest to largest), while ascending=False indicates descending order (largest to smallest).
  • Key Point: You can sort by multiple columns.

9. Data Merging (Merge)

  • Problem: Merge two DataFrames based on a specific column (e.g., 'ID').
  • Solution:
import pandas as pd

# DataFrame 1
df1 = pd.DataFrame({'ID': [1, 2, 3], 'Name': ['Alice', 'Bob', 'Charlie']})

# DataFrame 2
df

<ins class="adsbygoogle"
    style="display:block"
    data-ad-client="ca-pub-1480979447036150"
    data-ad-slot="2902356472"
    data-ad-format="auto"
    data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>