python - 使用 loc 替换值会出错
问题描述
我的代码如下所示:
import pandas as pd
df = pd.read_excel("Energy Indicators.xls", header=None, footer=None)
c_df = df.copy()
c_df = c_df.iloc[18:245, 2:]
c_df = c_df.rename(columns={2: 'Country', 3: 'Energy Supply', 4:'Energy Supply per Capita', 5:'% Renewable'})
c_df['Energy Supply'] = c_df['Energy Supply'].apply(lambda x: x*1000000)
print(c_df)
c_df = c_df.loc[c_df['Country'] == ('Korea, Rep.')] = 'South Korea'
当我运行它时,我收到错误“'str' has no attribute 'loc'”。似乎它告诉我我不能在数据帧上使用 loc 。我想做的就是替换这个值,所以如果有更简单的方法,我会全神贯注。
解决方案
我建议使用df.replace
:
df = df.replace({'c_df':{'Korea, Rep.':'South Korea'}})
上面的代码仅在列中替换Korea, Rep.
为。看看文档,它解释了我上面使用的嵌套字典语法:South Korea
c_df
df.replace
嵌套字典,例如,{'a': {'b': nan}},读法如下:在列'a' 中查找值'b' 并将其替换为nan。您也可以嵌套正则表达式。请注意,列名(嵌套字典中的顶级字典键)不能是正则表达式。
示例:
# Original dataframe:
>>> df
c_df whatever
0 Korea, Rep. abcd
1 x abcd
2 Korea, Rep. abcd
3 y abcd
# After df.replace:
>>> df
c_df whatever
0 South Korea abcd
1 x abcd
2 South Korea abcd
3 y abcd
推荐阅读
- makefile - 如何在 NMake 中创建和使用多行字符串变量?
- mysql - 如何从 aws 实例中读取密钥并添加到我的 mysql 查询中?
- flutter - Flutter 容器布局行为
- php - 多个域和一个文件夹 - 如何管理 sitemap.xml?
- javascript - Sencha Touch Picker show() 与最后一次选择
- python - 使用 sqlalchemy 进行批量更新
- javascript - Javascript根据文本框值检查表单中的单选按钮
- c++ - 多维数组c ++中数组下标的无效类型'int [int]'
- git - 更改分支的父级
- azure - 了解 Azure 通知中心限制的 API