Python 将大写应用于熊猫数据框中的列

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

Applying uppercase to a column in pandas dataframe

pythonpython-2.7pandas

提问by Gil5Ryan

I'm having trouble applying upper case to a column in my DataFrame.

我在将大写应用于 DataFrame 中的列时遇到问题。

dataframe is df.

数据框是df.

1/2 IDis the column head that need to apply UPPERCASE.

1/2 ID是需要应用大写的列头。

The problem is that the values are made up of three letters and three numbers. For example rrr123is one of the values.

问题是这些值由三个字母和三个数字组成。例如rrr123是值之一。

df['1/2 ID'] = map(str.upper, df['1/2 ID'])

I got an error:

我有一个错误:

TypeError: descriptor 'upper' requires a 'str' object but received a 'unicode' error.

TypeError: descriptor 'upper' requires a 'str' object but received a 'unicode' error.

How can I apply upper case to the first three letters in the column of the DataFrame df?

如何将大写应用于 DataFrame 列中的前三个字母df

采纳答案by Di Zou

This should work:

这应该有效:

df['1/2 ID'] = map(lambda x: str(x).upper(), df['1/2 ID'])

and should you want all the columnsnames to be in uppercase format:

如果您希望所有columns名称都为大写格式:

df.columns = map(lambda x: str(x).upper(), df.columns)

回答by bakkal

str.upper()wants a plain old Python 2 string

str.upper()想要一个普通的旧 Python 2 字符串

unicode.upper()will want a unicode not a string (or you get TypeError: descriptor 'upper' requires a 'unicode' object but received a 'str')

unicode.upper()需要一个 unicode 而不是字符串(或者你得到 TypeError: descriptor 'upper' requires a 'unicode' object but received a 'str')

So I'd suggest making use of duck typing and call .upper()on each of your elements, e.g.

所以我建议使用鸭子打字并调用.upper()你的每个元素,例如

df['1/2 ID'].apply(lambda x: x.upper(), inplace=True)

回答by EdChum

If your version of pandas is a recent version then you can just use the vectorised string method upper:

如果您的熊猫版本是最新版本,那么您可以使用矢量化字符串方法upper

df['1/2 ID'] = df['1/2 ID'].str.upper()

This method does not work inplace, so the result must be assigned back.

此方法不能就地工作,因此必须将结果分配回。