I'm trying to read integer values 10, 12, 2 from the second column of the excel sheet and store it to variables using python.
provided link to the png image representing cells in excel sheet
[https://i.stack.imgur.com/82por.png]
Using below code I'm able to read the entire data - Parrot(10)
whereas i want integer value of 10
# Import pandas
import pandas as pd
# Load csv
df = pd.read_csv("data.csv")
abc = df['Birds'].iloc[0]
CodePudding user response:
Since the question is actually 'how do I extract the number from a mixed string of numbers and letters' you probably want a regex.
import re
cell = "Parrot(10)"
matches = re.search(r"([0-9] )", cell)
number = int(matches.group(1))
There are other approaches, but this is probably the simplest for the dataset in question.
References
https://docs.python.org/3/howto/regex.html
CodePudding user response:
For this specific case you can use list comprehension and join function.
Code:
abc = "Parrot(10)"
number = int("".join([ch for ch in abc if ch.isdigit()]))
print(number)
CodePudding user response:
# 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]
This is finding the index of the opening bracket then adding 1 to find the first number then ignoring the closing bracket but only going to -1