使用正则表达式 returns nonetype 提取整数的函数
function to extract integer with regex returns nonetype
我写了一个函数来从字符串中提取整数。字符串示例如下,它是我的数据框中的一列。
我得到的输出在方括号中,里面有很多数字。我想使用这些数字进一步计算,但是当我检查它是什么时,它不是整数,而是 Nonetype。这是为什么?以及如何将它转换为整数,以便我可以找到 .sum() 或 .mean() 以及我得到的输出数字?理想情况下,我希望提取的整数作为另一列,例如 str.extract(regex, inplace=True).
这是我的部分数据,它是我的数据框 df2017 中的一列
Bo medium lapis 20 cash pr gr
Porte monnaie dogon vert olive 430 euros carte
Bo noires 2015 fleurs clips moins brillant 30 ...
Necklace No 20 2016 80€ carte Grecs 20h00 salo...
Bo mini rouges 30 carte 13h it
Necklace No 17 2016 100€ cash pr US/NYC crois ...
Chocker No 1 2016 + BO No 32 2016 70€ cash pr …
这是我的代码
def extract_int_price():
text=df2017['Items'].astype(str)
text=text.to_string()
amount=[int(x) for x in re.findall('(?<!No\s)(?<!new)(?!2016)(\d{2,4})+€?', text)]
print (amount)
谢谢!
您想使用 str.findall
or str.extractall
:
In [11]: REGEX = '(?<!No\s)(?<!new)(?!2016)(\d{2,4})+€?'
In [12]: s = df2017['Items']
In [13]: s.str.findall(REGEX)
Out[13]:
0 [20]
1 [430]
2 [2015, 30]
3 [016, 80, 20, 00]
4 [30, 13]
5 [016, 100]
6 [016, 016, 70]
dtype: object
In [14]: s.str.extractall(REGEX)
Out[14]:
0
match
0 0 20
1 0 430
2 0 2015
1 30
3 0 016
1 80
2 20
3 00
4 0 30
1 13
5 0 016
1 100
6 0 016
1 016
2 70
一般来说 extractall
是首选,因为它让你保持在 numpy 中而不是使用一系列 python 列表。
如果您的问题是求整数之和,那么您可以简单地:
sum(int(x) for x in ...)
但是,如果您的问题出在正则表达式上,那么您应该考虑改进您的过滤机制(应该输入什么)。您也可以考虑手动(虽然不理想)逐字过滤(确定哪个词不相关)。
你的函数 returns None
因为你忘记了 return
语句。因为 Python 中的每个函数都有一个 return 值,所以缺少 return
语句就像 returning None
.
我写了一个函数来从字符串中提取整数。字符串示例如下,它是我的数据框中的一列。 我得到的输出在方括号中,里面有很多数字。我想使用这些数字进一步计算,但是当我检查它是什么时,它不是整数,而是 Nonetype。这是为什么?以及如何将它转换为整数,以便我可以找到 .sum() 或 .mean() 以及我得到的输出数字?理想情况下,我希望提取的整数作为另一列,例如 str.extract(regex, inplace=True).
这是我的部分数据,它是我的数据框 df2017 中的一列
Bo medium lapis 20 cash pr gr
Porte monnaie dogon vert olive 430 euros carte
Bo noires 2015 fleurs clips moins brillant 30 ...
Necklace No 20 2016 80€ carte Grecs 20h00 salo...
Bo mini rouges 30 carte 13h it
Necklace No 17 2016 100€ cash pr US/NYC crois ...
Chocker No 1 2016 + BO No 32 2016 70€ cash pr …
这是我的代码
def extract_int_price():
text=df2017['Items'].astype(str)
text=text.to_string()
amount=[int(x) for x in re.findall('(?<!No\s)(?<!new)(?!2016)(\d{2,4})+€?', text)]
print (amount)
谢谢!
您想使用 str.findall
or str.extractall
:
In [11]: REGEX = '(?<!No\s)(?<!new)(?!2016)(\d{2,4})+€?'
In [12]: s = df2017['Items']
In [13]: s.str.findall(REGEX)
Out[13]:
0 [20]
1 [430]
2 [2015, 30]
3 [016, 80, 20, 00]
4 [30, 13]
5 [016, 100]
6 [016, 016, 70]
dtype: object
In [14]: s.str.extractall(REGEX)
Out[14]:
0
match
0 0 20
1 0 430
2 0 2015
1 30
3 0 016
1 80
2 20
3 00
4 0 30
1 13
5 0 016
1 100
6 0 016
1 016
2 70
一般来说 extractall
是首选,因为它让你保持在 numpy 中而不是使用一系列 python 列表。
如果您的问题是求整数之和,那么您可以简单地:
sum(int(x) for x in ...)
但是,如果您的问题出在正则表达式上,那么您应该考虑改进您的过滤机制(应该输入什么)。您也可以考虑手动(虽然不理想)逐字过滤(确定哪个词不相关)。
你的函数 returns None
因为你忘记了 return
语句。因为 Python 中的每个函数都有一个 return 值,所以缺少 return
语句就像 returning None
.