【问题标题】:Read a specific column of a certain cell range and store the values using Pandas读取某个单元格范围的特定列并使用 Pandas 存储值
【发布时间】:2015-12-10 21:42:45
【问题描述】:

我正在尝试找出一种方法来从特定单元格范围内的特定列中读取数据并使用 pandas 将其存储到数组中。

例如,我的 Excel 工作表包括:


测试 | p

食物|价格

鸡肉| 8.54

牛肉 |6.73

蔬菜| 3.2

总价|18.47

注意:第一行有一个空格是有原因的。 注:|表示细胞分离。

我正在尝试获取从 B3 行到 B5 行的价格值,并通过 [8.54,6.73,3.2] 将它们存储到一个数组中。

到目前为止我的代码是:

import pandas as pd

xl_workbook = pd.ExcelFile("readme.xlsx")  # Load the excel workbook
df = xl_workbook.parse("Sheet1")  # Parse the sheet into a dataframe
x1_list = df['p'].tolist()  # Cast the desired column into a python list
print(x1_list)

然后结果为 [nan, u'price',8.54,6.73,3.2]

如果我只想读取值 8.54、6.73 和 3.2,得到 [8.54,6.73,3.2],我该怎么做?

有没有办法抓取某个单元格范围的某个列?

【问题讨论】:

  • 切片不适合你吗?前 - x1_list = df['p'].tolist()[2:]
  • 你需要这个列表吗? df['p'].iloc[1:]会给你一个系列,df['p'].iloc[1:].tolist()会给你一样的列表
  • 可能我会尝试,但如果第一行完全为空,我会用什么来引用特定列?我不能正确使用 x1_list = df['p'].tolist() 吗?
  • @EdChum,如果 p 不存在,例如如果第一行是空的,我怎么能做到这一点?
  • 它仍然应该被分配一个序数值,所以如果第二列那么df[1].iloc[1:]应该可以工作

标签: python excel list pandas cell


【解决方案1】:

如前所述,您可以在 Pandas 中使用 read_excel。这假设您具有一致的格式。

import pandas as pd

# define the file name and "sheet name"
fn = 'Book1.xlsx'
sn = 'Sheet1'

data = pd.read_excel(fn, sheetname=sn, index_col=0, skiprows=1, header=0, skip_footer=1)

【讨论】:

  • 谢谢,我一定会试一试的。 C:
  • 我尝试了这段代码,但收到一条错误消息:parser_f() got an unexpected keyword argument 'sheetname'
  • 您使用的是什么版本的 Pandas?我在 16.2
猜你喜欢
  • 1970-01-01
  • 2017-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-08
相关资源
最近更新 更多