用于大写列的lambda代码不起作用

时间:2017-10-11 17:08:17

标签: python-3.x pandas numpy lambda

当我执行下面的Python 3.4.4代码来大写ident列下的值时,我没有错误,但我的输出没有大写。需要帮助找出问题所在。

import pandas as pd
import numpy as np
#Create a dataframe

data = {'ident': ['Jack', 'Mary', 'Teresa', 'James', 'Anna'], 
        'year': [2001, 2002, 2003, 2004, 2007], 
        'reports': [67, 5, 36, 9, 14],
        'scope': [17, 102, 57, 49, 77]
        }
df = pd.DataFrame(data, index = ['Bahia', 'Pico', 'Santa Fe', 'Maine', 
'Zuma'])
#Create a capitalizer function
capitalize = lambda x: x.upper()

#Create a capitalizing function over the column 'ident'

df['ident'].apply(capitalize)
print (df)

3 个答案:

答案 0 :(得分:2)

grep

答案 1 :(得分:1)

不会直接保存对数据框的更改。取代

df['ident'].apply(capitalize)

df['ident'] = df['ident'].apply(capitalize)

它会起作用。

所以完整的代码如下:

import pandas as pd
import numpy as np
#Create a dataframe

data = {'ident': ['Jack', 'Mary', 'Teresa', 'James', 'Anna'],
        'year': [2001, 2002, 2003, 2004, 2007],
        'reports': [67, 5, 36, 9, 14],
        'scope': [17, 102, 57, 49, 77]
        }
df = pd.DataFrame(data, index = ['Bahia', 'Pico', 'Santa Fe', 'Maine','Zuma'])
#Create a capitalizer function
capitalize = lambda x: x.upper()

#Create a capitalizing function over the column 'ident'

df['ident'] = df['ident'].apply(capitalize)
print (df)

或者做得更好(imho)df.ident=df.ident.str.upper()

答案 2 :(得分:1)

您需要将结果分配回df ['ident']

df['ident'] = df['ident'].apply(capitalize)

虽然我只是使用

df['ident'] = df['ident'].str.upper()