Reputation: 13
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.sstatic.net/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]
Upvotes: 1
Views: 364
Reputation: 202
# 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
Upvotes: 1
Reputation: 13
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)
Upvotes: 1
Reputation: 5954
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.
https://docs.python.org/3/howto/regex.html
Upvotes: 1