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

2024-09-24 18:59:51 发布

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

样本数据:

|   | 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"

预期结果:

我需要一个例外的专栏,可能现在不可用,但在未来它可能会来。所以帮我解决这个问题。你知道吗


Tags: csvintestdownloadsnotusers样本progress
1条回答
网友
1楼 · 发布于 2024-09-24 18:59:51

使用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的头文件(这不会读取整个文件!)。你知道吗

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))

最后,要填充缺少的列,请使用set difference并调用df.assign

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

相关问题 更多 >