pandas 使用pandas-Python 3遍历excel中的行和列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41718085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:48:38  来源:igfitidea点击:

iterate through rows and columns in excel using pandas-Python 3

excelpython-3.xloopspandas

提问by reuben

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

我有一个用以下代码阅读的 Excel 电子表格:

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

With the sheet that I want inside the spreadsheet being CCG

我想要在电子表格中的工作表是 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 2and col3for rows that contain both aand x. So the proposed output for this table would be: col1=[1,9], col2=[2,10]

我将如何编写代码获取的价值col 2,并col3同时包含行ax。因此,建议输出此表将是:col1=[1,9]col2=[2,10]

回答by MaxU

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:

Excel文件:

enter image description here

在此处输入图片说明

In [243]: fn = r'C:\Temp\.data718085.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

回答by Clusks

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:

然后从这里,您可以将所有值作为 numpy 数组返回:

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

回答by reuben

Managed to create a countthat iterates until it finds aadds +1 to the countand only appends to the list indexif 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

设法创建一个count迭代直到它找到a将 +1 添加到count并且仅index当它在 x 所在的范围之间时才附加到列表中,一旦我有了索引,我就会搜索第 2 列和第 3 列,并为指数