gpt4 book ai didi

python - 如何使用 Pandas 从 Excel 中读取某些列 - Python

转载 作者:IT老高 更新时间:2023-10-28 20:59:04 25 4
gpt4 key购买 nike

我正在阅读 Excel 工作表,并且我想阅读某些列:第 0 列,因为它是行索引,第 22:37 列。现在这就是我要做的:

import pandas as pd
import numpy as np
file_loc = "path.xlsx"
df = pd.read_excel(file_loc, index_col=None, na_values=['NA'], parse_cols = 37)
df= pd.concat([df[df.columns[0]], df[df.columns[22:]]], axis=1)

但我希望有更好的方法来做到这一点!我知道如果我这样做 parse_cols=[0, 22,..,37] 我可以做到,但对于大型数据集,这没有意义。

我也这样做了:

s = pd.Series(0)
s[1]=22
for i in range(2,14):
s[i]=s[i-1]+1
df = pd.read_excel(file_loc, index_col=None, na_values=['NA'], parse_cols = s)

但它会读取前 15 列,即 s 的长度。

最佳答案

您可以像这样使用列索引(字母):

import pandas as pd
import numpy as np
file_loc = "path.xlsx"
df = pd.read_excel(file_loc, index_col=None, na_values=['NA'], usecols="A,C:AA")
print(df)

Corresponding documentation :

usecols : int, str, list-like, or callable default None

  • If None, then parse all columns.

  • If str, then indicates comma separated list of Excel column letters and column ranges (e.g. “A:E” or “A,C,E:F”). Ranges are inclusive of both sides.

  • If list of int, then indicates list of column numbers to be parsed.

  • If list of string, then indicates list of column names to be parsed.

    New in version 0.24.0.

  • If callable, then evaluate each column name against it and parse the column if the callable returns True.

Returns a subset of the columns according to behavior above.

New in version 0.24.0.

关于python - 如何使用 Pandas 从 Excel 中读取某些列 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33655127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com