簡體   English   中英

使用loc替換值會產生錯誤

[英]Using loc to replace values gives error

我的代碼如下:

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”沒有屬性“ loc””。 似乎是在告訴我無法在數據幀上使用loc。 我要做的就是替換值,因此,如果有更簡單的方法,我將不知所措。

我建議使用df.replace

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

上面的代碼僅在c_dfc_df South Korea替換了Korea, Rep. 看一下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

做就是了

c_df.loc[c_df['Country'] == ('Korea, Rep.')] = 'South Korea'

代替

c_df = c_df.loc[c_df['Country'] == ('Korea, Rep.')] = 'South Korea'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM