从Python pandas中的列名称获取列索引

2024-04-19 06:17:35 发布

您现在位置:Python中文网/ 问答频道 /正文

在R中,当需要根据可以执行的列的名称检索列索引时

idx <- which(names(my_data)==my_colum_name)

有没有办法对pandas数据帧进行同样的处理?


Tags: 数据name名称pandaswhichdatanamesmy
3条回答

DSM的解决方案是有效的,但是如果您想要一个直接等价于which的解决方案,您可以(df.columns == name).nonzero()

下面是一个通过列表理解的解决方案。cols是要为其获取索引的列的列表:

[df.columns.get_loc(c) for c in cols if c in df]

当然,您可以使用.get_loc()

In [45]: df = DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})

In [46]: df.columns
Out[46]: Index([apple, orange, pear], dtype=object)

In [47]: df.columns.get_loc("pear")
Out[47]: 2

尽管说实话,我自己并不经常需要这个。通常按名称访问会按我的要求进行(df["pear"]df[["apple", "orange"]],或者可能是df.columns.isin(["orange", "pear"])),尽管我可以肯定地看到您需要索引号的情况。

相关问题 更多 >