简体   繁体   中英

print column values of one dataframe based on the column values of another dataframe

在此处输入图像描述在此处输入图像描述

So here is my first dataframe df1. In the columns, Starting DOY and Ending DOY, for example, 3.0 and 6.0, I want to print column values By, Bz, Vsw etc of another dataframe df2 by matching it with column DOY

Here is a simple tutorial how you can do it:

from pandas import DataFrame

if __name__ == '__main__':
    data1 = {'Starting DOY': [3.0, 3.0, 13.0],
             'Ending DOY': [6.0, 6.0, 15.0]}

    data2 = {'YEAR': [1975, 1975, 1975],
             'DOY': [1.0, 3.0, 6.0],
             'HR': [0, 1, 2],
             'By': [-7.5, -4.0, -3.6],
             'Bz': [0.2, 2.4, -2.3],
             'Nsw': [999.9, 6.2, 5.9],
             'Vsw': [9999.0, 476.0, 482.0],
             'AE': [181, 138, 86]}

    df1 = DataFrame(data1, columns=['Starting DOY',
                                    'Ending DOY'])

    df2 = DataFrame(data2, columns=['YEAR', 'DOY',
                                    'HR', 'By', 'Bz',
                                    'Nsw', 'Vsw', 'AE'])

    for doy in df1.values:
        start_doy = doy[0]
        end_doy = doy[1]
        for val in df2.values:
            year = val[0]
            current_doy = val[1]
            hr = val[2]
            By = val[3]
            Bz = val[4]
            Nsw = val[5]
            Vsw = val[6]
            AE = val[7]
            if start_doy <= current_doy <= end_doy:
                print("For DOY {}".format(current_doy))
                print("By: {}".format(By))
                print("Bz: {}".format(Bz))
                print("Vsw: {}".format(Vsw))
                print("--------------------")

Ouput:

For DOY 3.0
By: -4.0
Bz: 2.4
Vsw: 476.0
--------------------
For DOY 6.0
By: -3.6
Bz: -2.3
Vsw: 482.0
--------------------
For DOY 3.0
By: -4.0
Bz: 2.4
Vsw: 476.0
--------------------
For DOY 6.0
By: -3.6
Bz: -2.3
Vsw: 482.0
--------------------

I think the easiest way about this would be:

>>> df1 = pd.DataFrame([[1,2],[3,4],[5,6]], columns=["Starting DOY", "Ending DOY"])
>>> df2 = pd.DataFrame([[6,5,8, 1.5],[4,3,9, 3.5],[2,1,5, 5.5]], columns=["By", "Bz", "Vsw", "DOY"])
>>> df1.apply(lambda row: df2[(df2['DOY'] >= row[0]) & (df2['DOY'] <= row[1])], axis=1)
0       By  Bz  Vsw  DOY
0   6   5    8  1.5
1       By  Bz  Vsw  DOY
1   4   3    9  3.5
2       By  Bz  Vsw  DOY
2   2   1    5  5.5
dtype: object

Also depending on what you want the output for, and how you would need to format it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM