根据另一个数据框的列值打印一个数据框的列值

时间:2020-08-07 06:17:13

标签: python pandas numpy matplotlib math

enter image description here enter image description here

这是我的第一个数据帧df1。在“开始DOY”和“结束DOY”列(例如3.0和6.0)中,我想通过将其与DOY列匹配来打印另一个数据帧df2的列值By,Bz,Vsw等。

2 个答案:

答案 0 :(得分:0)

这是一个简单的教程,您可以怎么做:

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("--------------------")

输出:

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

答案 1 :(得分:0)

我认为最简单的方法是:

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

还取决于您要输出的内容以及格式化的方式。