Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 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 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...