如何在列中大写pandas对象而不将其转换为字符串?

bpsygsoo  于 2023-04-19  发布在  其他
关注(0)|答案(2)|浏览(520)

我想在列表中大写一个pandas对象,而不将其转换为字符串进行匹配。
这是数据集:
| 色谱柱A|B栏|
| --------------|--------------|
| [苹果派,香蕉奶昔,巧克力冰淇淋]||
| [鸡肉面,羊排,青柠汁]||
我在等B栏
| 色谱柱A|B栏|
| --------------|--------------|
| [苹果派,香蕉奶昔,巧克力冰淇淋]|【苹果派、香蕉奶昔、巧克力冰淇淋】|
| [鸡肉面,羊排,青柠汁]|【鸡肉面、羊排、青柠汁】|

wpx232ag

wpx232ag1#

在列表解析中使用str.title来处理每个单词的大写首字母,因为str.capitalize只转换第一个单词的首字母:

df['Column B'] = [[y.title() for y in x] for x in df['Column A']]
df['Column C'] = [[y.capitalize() for y in x] for x in df['Column A']]
print (df)
                                            Column A  \
0  [apple pie, banana milkshake, chocolate ice cr...   
1          [chicken noodles, lamb chops, lime juice]   

                                            Column B  \
0  [Apple Pie, Banana Milkshake, Chocolate Ice Cr...   
1          [Chicken Noodles, Lamb Chops, Lime Juice]   

                                            Column C  
0  [Apple pie, Banana milkshake, Chocolate ice cr...  
1          [Chicken noodles, Lamb chops, Lime juice]
2q5ifsrm

2q5ifsrm2#

使用pandas.DataFrame.apply

# import required module
import pandas as pd
import numpy as np

# create fake data
df = pd.DataFrame({
    'Column A': [['apple pie', 'banana milkshake', 'chocolate ice cream'], ['chicken noodles', 'lamb chops', 'lime juice']],
})

# create column b, c
df['Column B'] = df['Column A'].apply(lambda x: [y.title() for y in x])
df['Column C'] = df['Column A'].apply(lambda x: [y.capitalize() for y in x])

相关问题