Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

python - Pandas df.apply does not modify DataFrame

I am just starting pandas so please forgive if this is something stupid.

I am trying to apply a function to a column but its not working and i don't see any errors also.

 capitalizer = lambda x: x.upper()
    for df in pd.read_csv(downloaded_file, chunksize=2, compression='gzip', low_memory=False):
        df['level1'].apply(capitalizer)
        print df
        exit(1)

This print shows the level1 column values same as the original csv not doing upper. Am i missing something here ?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

apply is not an inplace function - it does not modify values in the original object, so you need to assign it back:

df['level1'] = df['level1'].apply(capitalizer)

Alternatively, you can use str.upper, it should be much faster.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...