Pandas – 在一个系列中,将每个单词的第一个和最后一个字符转换成大写字母
在python中,如果我们希望只将每个单词的第一个字符转换成大写字母,我们可以使用capitalize()方法。或者我们可以只取字符串的第一个字符,用upper()方法将其改为大写。因此,为了将一个系列中每个单词的第一个和最后一个字符转换成大写字母,我们将使用类似的方法。首先,让我们在Pandas中创建一个系列。
例子:让我们创建一个Pandas系列
# importing pandas as pd
import pandas as pd
# Create the series
series = pd.Series(['geeks', 'for', 'geeks',
'pandas', 'series'])
# Print the series
print("Series:")
series
输出 :
一旦我们使用Pandas创建了一个系列,我们将使用map()函数对整个系列应用一个lambda()函数。lambda函数将使用切片法获取第一个字符,将其大写,并将字符串的其余部分添加到最后一个字符之前。最后一个字符再次被大写并添加到结果系列中。
示例 :
# Apply the lambda function to
# capitalize first and last
# character to each word
newSeries = series.map(lambda x: x[0].upper() + x[1:-1] + x[-1].upper())
# Print the resulting series
print("\nResulting Series :")
newSeries
输出 :