python - 如何使用 pandas 编写 Excel 中列的异常代码?

标签 python python-3.x pandas excel-automation

示例数据:

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

相关文章:

python - 查找列表元素的所有可能排列,直到组合达到给定的长度

python - 使用 python pandas 对大型 csv 文件的汇总统计

python - 在日期时间中转换 DataFrame 列类型

python - tf.keras 手动设备放置

python - 使用 matplotlib 保存散点图动画

python - 使用 node.js pm2 在虚拟环境中运行 python 脚本

python - Macro VS Micro VS Weighted VS Samples F1 分数

python - PyInstaller 中没有名为 'pandas._libs.tslibs.timedeltas' 的模块

python - 如何从新闻摘要中提取股票代码NUMBER?

python - 目前如何在Pygame中播放视频?