Pandas Series.str.capitalize() 方法



Pandas 中的Series.str.capitalize() 方法用於將 Series 或 Index 中每個字串的首字母大寫。此方法是一種方便的方法,可以標準化文字資料的字母大小寫,確保每個字串都以大寫字母開頭,其餘字母小寫。此操作類似於 Python 中的字串方法str.capitalize()

語法

以下是 Pandas Series.str.capitalize() 方法的語法:

Series.str.capitalize()

引數

Series.str.capitalize() 方法不接受任何引數。

返回值

Series.str.capitalize() 方法返回一個新的 Series,其中每個字串的首字母大寫,其他字母小寫。

示例 1

在這個示例中,我們透過將其應用於字串 Series 來演示Series.str.capitalize() 方法的基本用法。

import pandas as pd

# Create a Series of strings
s = pd.Series(['hi,', 'welcome to', 'tutorialspoint'])

# Display the input Series
print("Input Series")
print(s)

# Capitalize the first letter of each string
print("Series after calling the Capitalize:")
print(s.str.capitalize())

執行上述程式碼後,將產生以下輸出

Input Series
0               hi,
1        welcome to
2    tutorialspoint
dtype: object

Series after calling the Capitalize:
0               Hi,
1        Welcome to
2    Tutorialspoint
dtype: object

示例 2

此示例演示如何使用Series.str.capitalize() 方法格式化 DataFrame 中的“Day”列,將每個日期名稱轉換為正確的首字母大寫。

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({'Day': ['mon', 'tue', 'wed', 'thu', 'fri'],
                   'Subject': ['Math', 'english', 'science', 'music', 'games']})

print("Input DataFrame:")
print(df)

# Capitalize the first letter of each day
df.Day = df.Day.str.capitalize()

print("DataFrame after applying Capitalize:")
print(df)

以下是上述程式碼的輸出

Input DataFrame:
   Day  Subject
0  mon     Math
1  tue  english
2  wed  science
3  thu    music
4  fri    games
DataFrame after applying Capitalize:
   Day  Subject
0  Mon     Math
1  Tue  english
2  Wed  science
3  Thu    music
4  Fri    games

示例 3

在這個示例中,我們將Series.str.capitalize() 方法應用於索引物件。這展示瞭如何使用它來格式化 DataFrame 中的索引標籤。

import pandas as pd

# Create a DataFrame with an Index
df = pd.DataFrame({'Value': [1, 2, 3]}, index=['first', 'second', 'third'])

# Capitalize the first letter of each index label
df.index = df.index.str.capitalize()

print(df)

上述程式碼的輸出如下:

       Value
First      1
Second     2
Third      3
python_pandas_working_with_text_data.htm
廣告