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
180 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 Reply

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.


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

...