Pandas DataFrame で文字列を大文字に変更するには:
df['column name'] = df['column name'].str.upper()
Pandas DataFrame で文字列を大文字に変換する手順
ステップ1: DataFrameを作成する
まず、5 つの野菜 (すべて小文字) とその価格を含む DataFrame を作成しましょう。
import pandas as pd
data = {'Vegetables': ['broccoli', 'carrot', 'onion', 'celery', 'spinach'],
'Price': [2, 3, 1.5, 2.5, 1]
}
df = pd.DataFrame(data)
print(df)
ご覧のとおり、5 つの野菜はすべて小文字で表記されています。

ステップ2: Pandas DataFrameの文字列を大文字に変更する
次に、次のテンプレートを使用して文字列を大文字に変更します。
df['column name'] = df['column name'].str.upper()
私たちの例:
import pandas as pd
data = {'Vegetables': ['broccoli', 'carrot', 'onion', 'celery', 'spinach'],
'Price': [2, 3, 1.5, 2.5, 1]
}
df = pd.DataFrame(data)
df['Vegetables'] = df['Vegetables'].str.upper()
print(df)
Python でコードを実行すると、5 つの野菜がすべて大文字に変換されていることがわかります。

DataFrame の各値に小文字の単語が複数含まれている場合はどうなりますか?
たとえば、以下の DataFrame では、「Vegetables」列の各値に小文字の複数の単語/野菜が含まれています。
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)
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)
df['Vegetables'] = df['Vegetables'].str.upper()
print(df)
コードを実行すると、すべての野菜が大文字になっていることがわかります。

各単語の最初の文字を大文字にする
str.title() を使用すると、各単語の最初の文字を大文字にすることができます。
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)
df['Vegetables'] = df['Vegetables'].str.title()
print(df)
結果:

最初の単語の最初の文字のみを大文字にする
あるいは、最初の単語の最初の文字だけを大文字にし(他の文字はすべて小文字のままに)、
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)
df['Vegetables'] = df['Vegetables'].str.capitalize()
print(df)
結果は次のとおりです。
