示例数据:
| | 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"
预期结果:
我需要一个列的异常(exception),该列现在可能不可用,但将来可能会出现。所以请帮助我解决这个问题。
最佳答案
使用 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))
最后,要填充缺失的列,请获取设置的差异并调用df.assign
:
df = df.assign(**dict.fromkeys(set(columns).difference(df_columns), np.nan))
关于python - 如何使用 pandas 编写 Excel 中列的异常代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48779475/