Pandas:参考列名,不区分大小写
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36362432/
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
Pandas: Refer to column name, case insensitive
提问by Winterflags
Using Pandas DataFrame
, let's say I have a bunch of columns in a csvfile, and I want to be able to access any one of them via case insensitive name.
使用Pandas DataFrame
,假设我在一个csv文件中有一堆列,我希望能够通过不区分大小写的名称访问其中的任何一个。
import pandas as pd
df = pd.read_csv(path_to_csv, delimiter=",")
df2 = df["Size"]
The actual column name is "Size"
. What can I do so that df2 = df["sIZE"]
can also be accepted?
实际的列名称是"Size"
. 我该怎么做df2 = df["sIZE"]
才能被接受?
采纳答案by EdChum
you can just call str.lower
on the columns
:
你可以打电话str.lower
给columns
:
In [12]:
df = pd.DataFrame(columns=['Size','COLOUR','caTegory'])
df.columns
Out[12]:
Index(['Size', 'COLOUR', 'caTegory'], dtype='object')
In [14]:
df.columns = df.columns.str.lower()
df.columns
Out[14]:
Index(['size', 'colour', 'category'], dtype='object')
回答by Daniel Severo
Have you tried changing the column names using df.columns to all lower or upper case? You can do that using
您是否尝试使用 df.columns 将列名更改为全部小写或大写?你可以使用
df.columns = map(str.lower, df.columns)
df.columns = map(str.lower, df.columns)
Maybe that can solve your issue.
也许这可以解决您的问题。
回答by BlindDriver
Why not normalize the column names in df
?
为什么不规范化中的列名df
?
df.columns = [c.lower() for c in df.columns]