简体   繁体   English

如何在 python 中使用 if elif 和 delete 语句编写 for 循环?

[英]how to write a for loop with if elif and delete statement in python?

I have a dataframe with 5000 records.我有一个带有 5000 条记录的 dataframe。

Data:
        Month   Heat Number  wts   gcs 
         1        HA        8.2    98
         1        HB        7.6    86
         2        HB        4.2    76
         3        HC        6.9    46
         4        HD        7.4    36
         5        HD        9.8    26
         6        HF        10.8   16

The 2nd letter of the Heat number column denotes month.热号栏的第二个字母表示月份。

A for January一月

B for Feb B 代表二月

C for March and so on.. C 三月等..

Condition:健康)状况:

If the record in month column is 1, the corresponding value in heat number column should always be 'HA'如果月份列中的记录为 1,则热号列中的对应值应始终为“HA”

If month is 2, the corresponding value in heat number column should always be 'HB'如果月份为 2,则热号列中的对应值应始终为 'HB'

If month is 3, the corresponding value in heat number column should always be 'HC'如果月份为 3,则热量数列中的对应值应始终为“HC”

If month is 4, the corresponding value in heat number column should always be 'HD'如果月份为 4,则热量数列中的对应值应始终为“HD”

If month is 5, the corresponding value in heat number column should always be 'HE'如果月份为 5,则热量数列中的对应值应始终为“HE”

Any records with incorrect match should be deleted(that entire row in the dataframe should be deleted) Example in the data the 2nd row should be deleted since the month is 1 and heat number is HB(heat number should have been HA)任何匹配不正确的记录都应删除(应删除 dataframe 中的整行)示例数据中的第 2 行应删除,因为月份为 1 且热编号为 HB(热编号应为 HA)

Desired Output:

Month   Heat Number  wts   gcs 
 1        HA        8.2    98
 2        HB        4.2    76
 3        HC        6.9    46
 4        HD        7.4    36
 6        HF        10.8   16

We need create the condition dataframe first then merge我们需要先创建条件 dataframe 然后merge

df=df.merge(pd.DataFrame({'Month': [1,2,3,4,5,6],'Heat Number':['HA','HB','HC','HD','HE','HF']}),how='inner')
   Month Heat Number   wts  gcs
0      1         HA   8.2   98
1      2         HB   4.2   76
2      3         HC   6.9   46
3      4         HD   7.4   36
4      6         HF  10.8   16

This plays off of the ord function in python to filter out rows that do not match with the Month column:这使用python中的 ORD function 过滤掉与 Month 列不匹配的行:

(
    df.assign(temp=lambda x: [ord(word[-1]) - 64 for word in x["Heat Number"]])
    .query("Month == temp")
    .drop("temp", axis=1)
)

    Month   Heat Number wts gcs
0   1       HA          8.2 98
2   2       HB          4.2 76
3   3       HC          6.9 46
4   4       HD          7.4 36
6   6       HF         10.8 16

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

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