我知道这是StackOverflow中反复出现的主题,但我在其他帖子中很难找到解决这个问题的方法。
我只想为df.Description
中的每一个sring将sring(descrbing sth(的第一个字母大写
有人能告诉我为什么在这种情况下我不能在df.Description
上循环吗?
for idx in df.Description.index:
df.Description.iloc[idx] = df.Description.iloc[idx][0].capitalize()
+ df.Description.iloc[idx][1:]
df.head()
Out[22]:
Type of Technology ... Sector
0 CF4_TCE ... Dummy
1 CH4_TCE ... Dummy
2 CH4g_TCE ... Dummy
3 CH4n_TCE ... Dummy
4 CH4o_TCE ... Dummy
[5 rows x 7 columns]
df.Description
Out[24]:
0 Tetrafluoromethane (CF4) Total Carbon Emissions
1 Methane total carbon equivalent emissions
2 CH4 emissions from animals directly in Total C...
3 CH4 emissions from anaerobic waste decompostio...
4 Dummy technology converting CH4 emissions from...
...
362 conservation cost curve step for transport demand
363 conservation cost curve step for transport demand
364 conservation cost curve step for transport demand
365 conservation cost curve step for transport demand
366 joint diffusion constraint for transport conse...
Name: Description, Length: 367, dtype: object
提前感谢
以下来自@Marcel M的建议解决了这个问题:
df.Description = df.Description.str[0].str.upper() + df.Description.str[1:]
以下内容应该有效:
df.Description = df.Description.str[0].str.upper() + df.Description.str[1:]
如文档中所述,您可以使用列的.str
属性来访问各种字符串处理方法,这些方法模拟标准Python字符串操作,但适用于整个列。df.Description.str[0]
返回每个字符串的第一个字符的新Series对象。然后使用.str.upper()
将该字符大写。
一个更简单的替代方案可能是使用capitalize()
或可能的title()
,如下所示:
df.Description = df.Description.str.capitalize()
或
df.Description = df.Description.str.title()
然而,在您的情况下,这可能是不可取的,因为这会错误地将"CH4"分别更改为"CH4"或"CH4"。