Python .loc替换所有列值,而不仅仅是索引列
我的代码如下所示:Python .loc替换所有列值,而不仅仅是索引列,python,pandas,dataframe,Python,Pandas,Dataframe,我的代码如下所示: 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' G
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
您需要指明要更改的列,否则将假定您需要所有列。使用
.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]
从Pandas文档中获得的信息很长,但在这种情况下可能会有所帮助
正如@COLDSPEED在他的评论中提到的,你可以
df['Country Name'].replace(
['Korea, Rep.', 'Iran, Islamic Rep.', 'Hong Kong SAR, China'],
['South Korea', 'Iran', 'Hong Kong'],
inplace = True)
您需要指明要更改的列,否则将假定您需要所有列。使用
.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]
从Pandas文档中获得的信息很长,但在这种情况下可能会有所帮助
正如@COLDSPEED在他的评论中提到的,你可以
df['Country Name'].replace(
['Korea, Rep.', 'Iran, Islamic Rep.', 'Hong Kong SAR, China'],
['South Korea', 'Iran', 'Hong Kong'],
inplace = True)
psst,这里的
replace
的另一个很好的用例,甚至s=s.map(dict).fillna(s)
如果你发现replace
很慢..replace工作得很好。Thank.psst,这里是replace
的另一个很好的用例,甚至s=s.map(dict)。如果你发现replace
slow,那么fillna(s)
。replace工作得很好。谢谢。或者只使用inplace:df['Country Name']。替换(['Korea,Rep.','Iran,Islamic Rep.','hongkong SAR,China'],['South Korea','Iran','Hong'],inplace=True)或者只使用inplace:df['Country Name']。替换(['韩国,代表','伊朗,伊斯兰代表','中国香港特别行政区',['韩国','伊朗','香港'],inplace=True)