如何使用 pandas 为 excel 中的列编写异常代码?

How to code the exception for a column in excel using pandas?

示例数据:

|   | Status                  | Failed | In Progress | Passed | Untested |
|---|-------------------------|--------|-------------|--------|----------|
| 2 | P0 Dry Run - 13/02/18   | 2.0    |             | 143.0  | 5.0      |
| 3 | P1 Test Plan - 06/02/18 | 4.0    |             | 247.0  | 367.0    |
| 4 | P2 Test plan - 03/01/18 | 22.0   | 2.0         | 496.0  | 54.0     |

代码:

msft = pd.read_csv("C:\Users\gomathis\Downloads\week_071.csv") 
msft = msft[['Passed', 'Failed', 'Blocked', 'In Progress', 'Not_Implemented', 'Not Applicable', 'Clarification Opened', 'Untested']]
msft.to_csv("C:\Users\gomathis\Downloads\week_072.csv")

错误:

KeyError: "['Blocked'] not in index"

预期结果:

我需要一个列的例外,现在可能不可用,但将来可能会出现。所以相应地帮助我解决这个问题。

使用 csv.DictReader.fieldnames 属性,找出 CSV 中存在的列,然后找到这些列的交集。

首先,指定所需的列。

columns = ['Passed', 
           'Failed', 
           'Blocked', 
           'In Progress', 
           'Not_Implemented', 
           'Not Applicable', 
           'Clarification Opened', 
           'Untested']

path = "C:\Users\gomathis\Downloads\week_071.csv"   # we'll use this later

接下来,使用 csv.DictReader 读取 CSV 的 headers(这不会读取整个文件!)。

import csv
with open(path, 'r') as f:
    reader = csv.DictReader(f)
    df_columns = reader.fieldnames

现在,找到集合的交集,并把它传递给pd.read_csv中的usecols

df = pd.read_csv(path, usecols=set(columns).intersection(df_columns))

最后,要填充缺失的列,取集合差值并调用 df.assign:

df = df.assign(**dict.fromkeys(set(columns).difference(df_columns), np.nan))