简体   繁体   English

在 Python 中使用 Excel 文件作为 Pandas 数据框的映射

[英]Using Excel file as mapping for pandas dataframe in Python

I'm trying to use an excel "master list" of error codes and the larger group in which they belong to group errors by the larger group in a pandas data frame.我正在尝试使用错误代码的 excel“主列表”以及它们所属的较大组,按熊猫数据框中的较大组对错误进行分组。 I'm unsure of how to do this.我不确定如何做到这一点。 I previously tried adding the error codes to a dictionary with the group name as they key and grouping by that, but it wouldn't properly group the codes.我以前尝试将错误代码添加到字典中,并使用组名作为键并按其分组,但它不会正确地对代码进行分组。 I'll add examples of my master list and data frame below.我将在下面添加我的主列表和数据框的示例。

Master list:主列表:

CODE代码 Type 1类型 1 Type 2类型 2 Type 3类型 3 Type4类型4
Code A代码 A X X
Code B代码 B X X
Code C代码 C X X
Code D代码 D X X
Code E代码 E X X

and so on for 10 columns and 57 rows依此类推 10 列 57 行

DataFrame:数据框:

CODE代码 Numerator分子 Denominator分母 Error Rate错误率
CODE B代码B 6 6 10 10 0.6 0.6
CODE A代码 A 4 4 10 10 0.4 0.4
CODE C代码 9 9 10 10 0.9 0.9
CODE D代码 D 0 0 10 10 0 0

and so on for whichever error codes show up以此类推,以显示出现的任何错误代码

I'd Like for the output to be:我希望输出为:

CODE代码 Numerator分子 Denominator分母 Error Rate错误率
Type 1类型 1 15 15 10 10 1.5 1.5
Type 2类型 2 4 4 10 10 0.4 0.4
Type 4类型 4 0 0 10 10 0 0

and so on for appropriate groupings.等等以进行适当的分组。

How do I go about doing this?我该怎么做?

I've used dictionaries and I've used isin() with a list of types to no avail.我使用过字典,并且使用isin()和类型列表无济于事。

Say first dataframe df1 second df2说第一个数据帧 df1 第二个 df2

#convert Code to CODE in first dataframe with str.upper for standardization
df1.CODE = df1.CODE.str.upper()

#replace X with column names and remove nan values
df1["new"] = df1.filter(like="T").replace("X", pd.Series(df1.columns, df1.columns)).stack().to_numpy()

#replace CODE A,B,C,D,E with Type 1,2,3,4
df2["CODE"] = df2[["CODE"]].replace(df1[["CODE","new"]].set_index("CODE").to_dict()["new"],regex=True)

df2 df2

    CODE    Numerator   Denominator Error Rate
0   Type 1      6          10         0.6
1   Type 2      4          10         0.4
2   Type 1      9          10         0.9
3   Type 4      0          10         0.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM