简体   繁体   English

使用 Python 遍历与列匹配的日期

[英]Iterate through dates matching with columns using Python

I have a table file with 366 columns.我有一个包含 366 列的表格文件。 From these, one represents the targeted date and the other 365 represents the temperature of one day of the year.其中,一个代表目标日期,另一个 365 代表一年中某一天的温度。 I added a new column named “temperature” and I would like to fill in this column with the corresponding temperature value of my date field.我添加了一个名为“温度”的新列,我想用我的日期字段的相应温度值填写此列。 Hard to explain, please look at the example:很难解释,请看例子:

DateFin   b1_T_M01  b2_T_M01 Temperature
27-01-18    5.6      3.8   
06-01-18    5.6      4.2
02-01-18    6.3      4.6        4.6
01-01-18    3.2      5.9        3.2

From b x _TM x , the b refers to the day and M to the month.从 b x _TM x开始, b指日, M指月。 So for example “b1_T_M01” refers to the temperature value of day one of the month one (first of January).因此,例如“b1_T_M01”指的是第一个月第一天(一月一日)的温度值。 Said that I would like to reduce the number of dimensions and only to keep the information on the day of my interest.说我想减少维度的数量,只保留我感兴趣的那一天的信息。 As an example, for date 27-01-18 I would need the band 27 from month 01 (b27_TM01).例如,对于日期 27-01-18,我需要从 01 月(b27_TM01)开始的带 27。 I have no idea of how to iterate using different dimensions, I am frozen.我不知道如何使用不同的维度进行迭代,我被冻结了。 Does anyone have a clue of how to do that in an iteratively way using python?有没有人知道如何使用 python 以迭代方式做到这一点? Thank you very much for you attention!非常感谢您的关注!

You can build a string out of your date column, to get the right value:您可以从日期列中构建一个字符串,以获得正确的值:

df['DateFin'] = pd.to_datetime(df['DateFin'], dayfirst=True)

def my_date_string(date):
    return 'b' + str(date.day) + '_T_M' + '{:02d}'.format(date.month)


df['Temperature'] = df.apply(lambda row:
         row[my_date_string(row['DateFin'])]
         if my_date_string(row['DateFin']) in df.columns
         else '', axis=1)
print(df)

     DateFin  b1_T_M01  b2_T_M01 Temperature
0 2018-01-27       5.6       3.8            
1 2018-01-06       5.6       4.2            
2 2018-01-02       6.3       4.6         4.6
3 2018-01-01       3.2       5.9         3.2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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