如何获取和存储整数值内(..)在一个单元格在excel使用python变量



我正试图从excel表的第二列读取整数值10,12,2,并使用python将其存储到变量中。

提供了指向表示excel工作表

单元格的PNG图像的链接[https://i.stack.imgur.com/82por.png]

使用下面的代码,我能够读取整个数据-Parrot(10),而我想要10的整数值


# Import pandas
import pandas as pd
# Load csv
df = pd.read_csv("data.csv")
abc = df['Birds'].iloc[0]
# Import pandas
import pandas as pd
# Load csv
df = pd.read_csv("data.csv")
word = df['Birds'].iloc[0]
offset = word.find("(")
num = word[offset+1:-1]

这是查找左括号的索引然后加1得到第一个数字然后忽略右括号,只执行-1

由于问题实际上是'我如何从数字和字母的混合字符串中提取数字',您可能需要一个正则表达式。

import re
cell = "Parrot(10)"
matches = re.search(r"([0-9]+)", cell)
number = int(matches.group(1))

还有其他方法,但这可能是最简单的数据集。

引用

https://docs.python.org/3/howto/regex.html

对于这种特殊情况,您可以使用列表推导和连接函数。

代码:

abc = "Parrot(10)"
number = int("".join([ch for ch in abc if ch.isdigit()]))
print(number)

相关内容

最新更新