0

I have an excel spreadsheet that I read with this code:

df=pd.ExcelFile('/Users/xxx/Documents/Python/table.xlsx')
ccg=df.parse("CCG")

With the sheet that I want inside the spreadsheet being CCG

The sheet looks like this:

  col1  col2   col3    
x    a     1      2     
x    b     3      4    
x    c     5      6     
x    d     7      8
x    a     9      10
x    b     11     12
x    c     13     14
y    a     15     16
y    b     17     18
y    c     19     20
y    d     21     22
y    a     23     24

How would I write code that gets values of col 2 and col3 for rows that contain both a and x. So the proposed output for this table would be: col1=[1,9], col2=[2,10]

3 Answers 3

2

Try this:

df = pd.read_excel('/Users/xxx/Documents/Python/table.xlsx', 'CCG', index_col=0, usecols=['col1','col2']) \
       .query("index == 'x' and col1 == 'a'")

Demo:

Excel file:

enter image description here

In [243]: fn = r'C:\Temp\.data\41718085.xlsx'

In [244]: pd.read_excel(fn, 'CCG', index_col=0, usecols=['col1','col2']) \
            .query("index == 'x' and col1 == 'a'")
Out[244]:
  col1  col2
x    a     1
x    a     9
Sign up to request clarification or add additional context in comments.

3 Comments

its coming up with a syntax error on the new= line
You forgot to chain .parse("CCG").
@MaxU, SyntaxError: EOF while scanning triple-quoted string literal
1

You can do:

df = pd.read_excel('/Users/xxx/Documents/Python/table.xlsx'),sheetname='CCG', index_col=0)
filter = df[(df.index == 'x') & (df.col1 == 'a')]

Then from here, you can return all the values as a numpy array with:

filter['col2']
filter['col3']

Comments

0

Managed to create a count that iterates until it finds a adds +1 to the count and only appends to the list index if it is between the ranges that x is in, once i have the indices i search through col 2 and 3 and pull the values out for the indices

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.