首页 > 解决方案 > 数据框 - 更改嵌套变量

问题描述

我们正在讨论从 excel 导入的数据

ene2 = pd.read_excel('Energy Indicators.xls', index=False) 

最近我在帖子中询问,答案清晰,直接并带来了成功。

改变 Pandas 数据结构中元素的值

但是我更进一步,我有类似的(原文如此!)问题,分配变量不会改变任何东西。

让我们考虑数据结构

print(ene2.head())
               Country Energy Supply Energy Supply per Capita % Renewable's
    15             NaN    Gigajoules               Gigajoules             %
    16     Afghanistan     321000000                       10       78.6693
    17         Albania     102000000                       35           100
    18        Algeria1    1959000000                       51       0.55101
    19  American Samoa           ...                      ...      0.641026

238                            Viet Nam    2554000000                       28       45.3215
239           Wallis and Futuna Islands             0                       26             0
240                               Yemen     344000000                       13             0
241                              Zambia     400000000                       26       99.7147
242                            Zimbabwe     480000000                       32       52.5361
243                                 NaN           NaN                      NaN           NaN
244                                 NaN           NaN                      NaN           NaN

有些国家有索引(如 Algieria1 或 Australia12)我想将这些名称更改为 Algieria、Australia 等。

总共有 20 个条目需要更改。我开发了一种方法来做到这一点,但在最后一步失败了..

for value in ene2['Country']:
    if type(value) == float: # to cover NaN values
        continue

    x = re.findall("\D+\d", value) # to find those countries/elements which are with number

    while len(x) > 0: # this shows elements with number, otherwise answer is [], which is 0
        for letters in x: # to touch letters
            right = letters[:-1] # and get rid of the last number
            ene2.loc[ene2['Country'] == value, 'Country'] = right # THIS IS ELEMENT WHICH FAILS <= it does not chagne the value
        x = re.findall("\D+\d", value) # to bring the new value to the while loop

上面的代码应该完成任务,最终从名称中删除所有索引,但是代码 - ene2.loc[...] 以前可以工作,在这里,嵌套在哪里,什么也不做。

这种交换不起作用的情况是什么,我怎样才能克服问题a)以旧式方式b)以熊猫方式?

标签: pythonpandasdataframe

解决方案


该代码建议您已经使用 pandas,那么为什么不使用带有正则表达式的内置替换方法呢?

df = pd.DataFrame(data=["Afghanistan","Albania", "Algeria1", "Algeria9999"], columns=["Country"])
df["Country_clean"] = df["Country"].str.replace(r'\d+$', '')

输出:

print(df["Country_clean"])

0    Afghanistan
1        Albania
2        Algeria
3        Algeria
Name: Country, dtype: object

推荐阅读