Python 如何使 Pandas 数据框列标题全部小写?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19726029/
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-08-19 14:26:34  来源:igfitidea点击:

How can I make pandas dataframe column headers all lowercase?

pythonpandasdataframe

提问by natsuki_2002

I want to make all column headers in my pandas data frame lower case

我想让我的熊猫数据框中的所有列标题小写

Example

例子

If I have:

如果我有:

data =

  country country isocode  year     XRAT          tcgdp
0  Canada             CAN  2001  1.54876   924909.44207
1  Canada             CAN  2002  1.56932   957299.91586
2  Canada             CAN  2003  1.40105  1016902.00180
....

I would like to change XRAT to xrat by doing something like:

我想通过执行以下操作将 XRAT 更改为 xrat:

data.headers.lowercase()

So that I get:

所以我得到:

  country country isocode  year     xrat          tcgdp
0  Canada             CAN  2001  1.54876   924909.44207
1  Canada             CAN  2002  1.56932   957299.91586
2  Canada             CAN  2003  1.40105  1016902.00180
3  Canada             CAN  2004  1.30102  1096000.35500
....

I will not know the names of each column header ahead of time.

我不会提前知道每个列标题的名称。

采纳答案by Roman Pekar

You can do it like this:

你可以这样做:

data.columns = map(str.lower, data.columns)

or

或者

data.columns = [x.lower() for x in data.columns]

example:

例子:

>>> data = pd.DataFrame({'A':range(3), 'B':range(3,0,-1), 'C':list('abc')})
>>> data
   A  B  C
0  0  3  a
1  1  2  b
2  2  1  c
>>> data.columns = map(str.lower, data.columns)
>>> data
   a  b  c
0  0  3  a
1  1  2  b
2  2  1  c

回答by theister

If you want to do the rename using a chained method call, you can use

如果要使用链式方法调用进行重命名,可以使用

data.rename(
    columns=unicode.lower
)

(Python 2)

(蟒蛇 2)

or

或者

data.rename(
    columns=str.lower
)

(Python 3)

(蟒蛇 3)

回答by Anton Protopopov

You could do it easily with str.lowerfor columns:

您可以使用str.lowerfor轻松完成columns

df.columns = df.columns.str.lower()

Example:

例子:

In [63]: df
Out[63]: 
  country country isocode  year     XRAT         tcgdp
0  Canada             CAN  2001  1.54876  9.249094e+05
1  Canada             CAN  2002  1.56932  9.572999e+05
2  Canada             CAN  2003  1.40105  1.016902e+06

In [64]: df.columns = df.columns.str.lower()

In [65]: df
Out[65]: 
  country country isocode  year     xrat         tcgdp
0  Canada             CAN  2001  1.54876  9.249094e+05
1  Canada             CAN  2002  1.56932  9.572999e+05
2  Canada             CAN  2003  1.40105  1.016902e+06

回答by AnksG

Here is a simple way: data.columns = data.columns.str.lower()

这是一个简单的方法: data.columns = data.columns.str.lower()