Pandasライブラリを使用してPythonで文字列を大文字に変換する方法を紹介します。この記事では、Pandas DataFrameの特定の列に含まれる文字列を大文字に変換する方法を学びます。

Pandasで文字列を大文字に変換する

Pandasの str.upper() メソッドを使用して、DataFrameの特定の列の文字列を大文字に変換できます。以下にその使用例を示します。

import pandas as pd

# データフレームを作成
data = {'Vegetables': ['broccoli','carrot','onion','celery','spinach'], 'Price': [2,3,1.5,2.5,1]}
df = pd.DataFrame(data, columns = ['Vegetables', 'Price'])

# 'Vegetables'列の文字列を大文字に変換
df['Vegetables'] = df['Vegetables'].str.upper()

print(df)

このコードを実行すると、すべての野菜名が大文字に変換されます。

複数の単語を含む文字列を大文字に変換する

各値が複数の単語を含むDataFrameの場合でも、同じロジックを適用して文字列を大文字に変換できます。

import pandas as pd

# データフレームを作成
data = {'Vegetables': ['broccoli and cauliflower','carrot and cabbage','onion and basil','celery and kale','spinach and lettuce'], 'Price': [4,5.5,3.5,3,4.5]}
df = pd.DataFrame(data, columns = ['Vegetables', 'Price'])

# 'Vegetables'列の文字列を大文字に変換
df['Vegetables'] = df['Vegetables'].str.upper()

print(df)

このコードを実行すると、すべての野菜名が大文字に変換されます。

以上が、Pandasを使用してPythonで文字列を大文字に変換する方法です。このテクニックは、データの前処理やデータクレンジングの際に非常に役立ちます。.

投稿者 admin

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です