我知道这在StackOverflow中是一个经常出现的话题,但是我在其他的帖子中很难找到解决这个问题的方法。你知道吗
我只想为df.Description
中的每一个字母大写一个字母(描述某事物)
谁能告诉我为什么在这种情况下不能循环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:]
以下应起作用:
作为described in the documentation,您可以使用列的
.str
属性来访问各种字符串处理方法,这些方法模拟标准Python字符串操作,但处理整个列。df.Description.str[0]
返回每个字符串的第一个字符的新Series对象。然后.str.upper()
用于将该字符大写。你知道吗一个更简单的替代方法是这样使用^{} or possibly ^{} :
或者
然而,在您的案例中,这可能是不需要的,因为这将分别错误地将“CH4”更改为“CH4”或“CH4”。你知道吗
相关问题 更多 >
编程相关推荐