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
531 views
in Technique[技术] by (71.8m points)

python - I want to filter out a non-numeric value and calculate it's new value using two other columns in the dataframe (pandas)

I have a df that looks something like this:

col1 col2 col3
0.8 0.1 SP
0.9 0 SP
0.9 0.1 SP
0.7 SP 0.2
0.9 SP 0

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

1 Reply

0 votes
by (71.8m points)

This look like no reliable code, but still it could help.

df[df['col3']=='SP'] do the same as df.loc[df['col3']=='SP'], but 'df.loc' should be better for assigning. (when you try without .loc it will recommend use it for assign)

The code filter the rows where SP is in column 3, then assign.

df['col3'].loc[df['col3']=='SP']=1-df['col1'][df['col3']=='SP']-df['col2'][df['col3']=='SP']

EDIT

*Alternatives: 5 ways to apply an IF condition in Pandas DataFrame

df['col3']=df.apply(lambda x: 1-x['col1']-x['col2'] if x['col3'] == 'SP' else x['col3'],axis=1)

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

...