.loc将替换所有列的值,而不仅仅是索引列

2024-04-19 21:41:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码看起来像:

GDP = pd.read_excel("GDP_in.xls", skiprows=4)
GDP.loc[GDP['Country Name'] == 'Korea, Rep.'] = 'South Korea'
GDP.loc[GDP['Country Name'] == 'Iran, Islamic Rep.'] = 'Iran'
GDP.loc[GDP['Country Name'] == 'Hong Kong SAR, China'] = 'Hong Kong'
GDP = GDP.set_index(['Country Name'])
GDP = GDP.iloc[:, 49:59]

我原以为这只会更改“Country Name”列的值,但它正在更改所有列的值。例如,行中带有“Korea,Rep.”的所有列都已更改为第49-59列中的值“South Korea”。你知道吗

生成的df类似于:

               2006         2007         2008
United States  1e12         2e12        2.2e12
Iran           Iran         Iran         Iran
Australia      5e10         4e10         3e10 
South Korea   South Korea  South Korea  South Korea

Tags: 代码nameinreadexcelcountrylocpd
1条回答
网友
1楼 · 发布于 2024-04-19 21:41:11

您需要指明要更改的列,否则熊猫会假定您需要所有列。当使用.loc时,可以将行和列传递给它。.loc[row, col]所以只需输入它的国家名称。你知道吗

GDP = pd.read_excel("GDP_in.xls", skiprows=4)
GDP.loc[GDP['Country Name'] == 'Korea, Rep.', 'Country Name'] = 'South Korea'
GDP.loc[GDP['Country Name'] == 'Iran, Islamic Rep.', 'Country Name'] = 'Iran'
GDP.loc[GDP['Country Name'] == 'Hong Kong SAR, China', 'Country Name'] = 'Hong Kong'
GDP = GDP.set_index(['Country Name'])
GDP = GDP.iloc[:, 49:59]

熊猫文档中的This post很长,但在这种情况下可能会有所帮助。你知道吗

正如@COLDSPEED在他的评论中提到的,你可以

df['Country Name'].replace(
                         ['Korea, Rep.', 'Iran, Islamic Rep.', 'Hong Kong SAR, China'], 
                         ['South Korea', 'Iran', 'Hong Kong'],
                         inplace = True)

相关问题 更多 >