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
Applying uppercase to a column in pandas dataframe
提问by Gil5Ryan
I'm having trouble applying upper case to a column in my DataFrame.
我在将大写应用于 DataFrame 中的列时遇到问题。
dataframe is df
.
数据框是df
.
1/2 ID
is 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 rrr123
is 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 columns
names 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)