在字符串切片和使用列表理解方面遇到困难

问题描述 投票:0回答:1

我目前正在研究一个来自数据集的 pandas 数据框,其中包括 2012 年以来德国的进出口收入。为了清楚起见,我想添加另一列“大陆”并为每个国家分配其位置。我的数据框按国家和年份排序。片段如下所示:

国家 代码 ... 大陆
阿富汗 ST423 ... 4<-- desired result

“代码”中的第三个字符定义了大陆:1代表欧洲,2代表非洲,3代表美洲,4代表亚洲,5代表大洋洲。我正在尝试用大陆名称填充“大陆”列。

我尝试的是首先创建“代码”系列的列表

codelist = df["Code"].to_list()

然后我尝试(在未能实现我的目标之后)至少将数字添加到该列中,因此在“代码”中的每个值中进行第三个签名。但即使在这里我也未能做到这一点:

[codelist[x][2] for x in range(0,len(codelist)-1)]

它指出:“IndexError:字符串索引超出范围”,我不明白,因为

codelist[0][2] 

codelist[len(codelist)-1][2] 

两者都给出了积极的结果。

python pandas list-comprehension slice
1个回答
0
投票

这是因为

Code
列肯定包含至少一个长度小于3的字符串。

       Country   Code
0  Afghanistan  ST423
1            A     ST
2            B   None
3            C    XXX

      1 codelist = df["Code"].to_list()
----> 2 [codelist[x][2] for x in range(0,len(codelist)-1)]

IndexError: string index out of range

您可以使用

str
/
map
:

d = dict(enumerate(["Europe", "Africa", "Americas", "Asia", "Oceania"], start=1))

df["Continent"] = pd.to_numeric(df["Code"].str[2], errors="coerce").map(d)

另一种变体

extract
:

df["Continent"] = df["Code"].str.extract("..(\d)", expand=False).astype("Int8").map(d)

或者,如果您更喜欢 listcomp,您可以通过添加

if/else
语句来修复代码:

df["Continent"] = [
    d.get(int(c[2])) if c and len(c)>2 and c[2].isdigit()
    else None for c in df["Code"] # <-- change None if needed
]

输出:

print(df)

       Country   Code Continent
0  Afghanistan  ST423      Asia
1            A     ST       NaN
2            B   None       NaN
3            C    XXX       NaN
© www.soinside.com 2019 - 2024. All rights reserved.