【问题标题】:Dropping Columns with if statements, then adding exception使用 if 语句删除列,然后添加异常
【发布时间】:2022-07-06 02:58:57
【问题描述】:

我有这段代码通过 csv,为我找到有意义的列,然后删除不在列表中的列。它工作得很好,但我希望它删除所有未找到的列,除了一个名为“MATNR”的列。除了“MATNR”之外,我可以在 drop 语句中添加什么来允许我删除所有不需要的列?

# Import Data Quality Rules (useful attributes)
rexp = re.compile('\.([A-Z]+)')
found = []

with open('DataRules.csv') as f:
    for line in f:
        found.extend(rexp.findall(line))

# Get rid of columns that are not mentioned in rules (except MATNR)
df.drop(columns=([col for col in df if col not in found]), inplace=True)

# Get rid of duplicated rows
df = df.drop_duplicates()

【问题讨论】:

  • 您可以通过说df[found] 仅提取您想要的列。要添加 MATNR,请执行 df[found+['MATNR']]
  • found.remove('MATNR')?
  • [col for col in df if col not in found and col != 'MATNR']
  • df[['MATNR']]

标签: python pandas


【解决方案1】:
# Import Data Quality Rules (useful attributes)
rexp = re.compile('\.([A-Z]+)')
found = []

with open('DataRules.csv') as f:
    for line in f:
        found.extend(rexp.findall(line))

# Get rid of columns that are not mentioned in rules (except MATNR)
df.drop(columns=([col for col in df if col not in found and col != 'MATNR']), inplace=True)

# Get rid of duplicated rows
df = df.drop_duplicates()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    • 2012-09-04
    相关资源
    最近更新 更多