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

python - iterate row by row in two dataframes based on conditions

I have a dataframe named as dataframeA which contains following data,

ID     Date       From  TO    Type    Price
1   01/01/2020    C      D    AC       100
2   02/01/2020    C      D    AV       10
3   02/01/2020    A      B    AV       50
4   02/01/2020    D      C    BV       30
5   03/01/2020    A      B    AV       30
6   04/01/2020    B      C    BV       20
7   05/01/2020    B      C    BV       20

Following is my expected output as dataframeB:

    ID     Date       From   TO    Type    Price   VAR   VAR1
    1   01/01/2020    C      D    AC       50      D       1
    1'  01/01/2020    C      D    AC       50      D      Nan
    2   02/01/2020    C      D    AV       10      D      Nan
    3   02/01/2020    A      B    AV       30      B       3
    3'  02/01/2020    A      B    AV       20      B       3'
    4   02/01/2020    D      C    BV       30     Nan      1
    5   03/01/2020    A      B    AV       30      B       Nan
    6   04/01/2020    B      C    BV       20     Nan      3   
    7   05/01/2020    B      C    BV       20     Nan      3'

The current thinking is is to iterate dataframeA row by row, if the type = AC or AV , we append the row in a new dataframeB , and dataframeB['VAR'] = dataframeB['TO]. if the type = BV: I iterate dataframeB row by row, where the first row with dataframeB['TO'] = AC or AV , row1['VAR'] == row['FROM'] and VAR1 = NAN. if the price equals , I insert row in dataframeB with value VAR1 == ID if are not equals : I duplicate row and I change the price where row1['price']= row1['price'] - row['price'] and I add that id in the VAR1.

This is the code that I tried :

for index , row in dataframeA.iterrows():
    if (row['type'] == 'AC')| (row['type'] == 'AV') :
        dataframeB = dataframeB.append(row)
        dataframeB['VAR'] = dataframeB['VAR'].fillna(dataframeB['TO'])
    if row['type'] == 'BV':
        for index1 , row1 in dataframeB.iterrows(): 
            if  row['FROM] == row1['VAR'] &  row1['VAR'] == np.nan:
                dataframeB = dataframeB.append(row)

and I stucked in the part of duplicate row in dataframeA and change the price.


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

1 Reply

0 votes
by (71.8m points)
等待大神答复

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

...