首页 > 解决方案 > 使用 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 。我想做的就是替换这个值,所以如果有更简单的方法,我会全神贯注。

标签: pythonpandasdataframe

解决方案


我建议使用df.replace

df = df.replace({'c_df':{'Korea, Rep.':'South Korea'}})

上面的代码仅在列中替换Korea, Rep.为。看看文档,它解释了我上面使用的嵌套字典语法:South Koreac_dfdf.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

推荐阅读