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

python - Different Equation Applied to Specific Rows in DataFrame

I'm trying to add a column for density to a dataframe, which is calculated by the equation shown. I need the reference density to change at a certain row (row 66). I've tried two for loops and a for/else loop and they each use one of the densities for every row, rather than switching as I intend. I have defined all the variables, and am not getting any errors.

Attempt #1

for index, row in tem80df[tem80df['DREF'] <= 66].iterrows(): 
    density80 = density_crust * (1-(alpha * tem80df['TREF']))
for index, row in tem80df[tem80df['DREF'] > 66].iterrows():
    density80= density_mantle * (1- (alpha *tem80df['TREF']))

Attempt #2

for index, row in tem80df[tem80df['DREF'] <= 66].iterrows(): 
    density80 = density_crust * (1-(alpha * tem80df['TREF']))
else: 
    density80 = density_mantle * (1 - (alpha* tem80df['TREF']))

'DREF' and 'TREF' are column names. 'DREF' is the first column.

Help would be appreciated!

question from:https://stackoverflow.com/questions/65938346/different-equation-applied-to-specific-rows-in-dataframe

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

1 Answer

0 votes
by (71.8m points)
density_list = []
TR = <index of column TREF>

# get row count and loop through number of rows in dataframe
for i in range(0,tem80df.shape[0]):

    if i<=66:
        density80 = density_crust * (1-(alpha * tem80df.iloc[i:TR]))
        density_list.append(density80)

    else:
        density80= density_mantle * (1- (alpha *tem80df.iloc[i:TR]))
        density_list.append(density80)

tem80df['Density'] = density_list

TR is the index of column TREF, starting with the first column = 0.


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

2.1m questions

2.1m answers

60 comments

57.0k users

...