如何为循环编写干式Python

2024-10-03 21:24:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个大麻数据集,它有一个“效果”列,我正试图为不包含某些效果的毒株添加一个二进制“nice_-buds”列。代码如下:

nice_buds = []
undesired_effects = ["Sleepy", "Hungry", "Giggly", "Tingly", "Aroused", "Talkative"]

for row in sample["Effects"]:
    if "Sleepy" not in row and "Hungry" not in row and "Giggly" not in row and "Tingly" not in row and "Aroused" not in row and "Talkative" not in row:
        nice_buds.append(1)
    else:
        nice_buds.append(0)

sample["nice_buds"] = nice_buds

到目前为止,undesired_effects列表什么也没做,代码在提供所需输出方面工作得非常好

我的问题是,是否有一种更为“Pythonic”或“DRY”的方法来解决这个问题……


Tags: and代码innotrowniceeffects效果
2条回答

可以将all()与生成器表达式一起使用,以简化if语句

nice_buds = []
undesired_effects = ["Sleepy", "Hungry", "Giggly", "Tingly", "Aroused", "Talkative"]

for row in sample["Effects"]:
    if all(effect not in row for effect in undesired_effects):
        nice_buds.append(1)
    else:
        nice_buds.append(0)

sample["nice_buds"] = nice_buds

或使用any()&;检查是否存在影响:

nice_buds = []
undesired_effects = ["Sleepy", "Hungry", "Giggly", "Tingly", "Aroused", "Talkative"]

for row in sample["Effects"]:
    if any(effect in row for effect in undesired_effects):
        nice_buds.append(0)
    else:
        nice_buds.append(1)

sample["nice_buds"] = nice_buds

给定一个数据帧sample

  • 使用^{}
  • 使用^{}
  • 字符串可能是大写或小写,因此最好强制使用一个大小写,因为Giggly!=傻笑
  • for row in sample["Effects"]告诉我您正在使用数据帧。千万不要使用for-loopiterate through a dataframe
import pandas as pd
import numpy as np

# create dataframe
data = {'Effects': ['I feel great', 'I feel sleepy', 'I fell hungry', 'I feel giggly', 'I feel tingly', 'I feel aroused', 'I feel talkative']}

sample = pd.DataFrame(data)

|    | Effects          |
| -:|:        -|
|  0 | I feel great     |
|  1 | I feel sleepy    |
|  2 | I fell hungry    |
|  3 | I feel giggly    |
|  4 | I feel tingly    |
|  5 | I feel aroused   |
|  6 | I feel talkative |

undesired_effects = ["Sleepy", "Hungry", "Giggly", "Tingly", "Aroused", "Talkative"]

# words should be 1 case for matching, lower in this instance
undesired_effects = [effect.lower() for effect in undesired_effects]

# values to match as string with | (or)
match_vals = '|'.join(undesired_effects)

# create the nice buds column
sample['nice buds'] = np.where(sample['Effects'].str.lower().str.contains(match_vals), 0, 1)

display(sample)

|    | Effects          |   nice buds |
| -:|:        -|      :|
|  0 | I feel great     |           1 |
|  1 | I feel sleepy    |           0 |
|  2 | I fell hungry    |           0 |
|  3 | I feel giggly    |           0 |
|  4 | I feel tingly    |           0 |
|  5 | I feel aroused   |           0 |
|  6 | I feel talkative |           0 |

相关问题 更多 >