簡體   English   中英

Pandas 數據框從交叉口的字典創建

[英]Pandas dataframe create from dict of crossings

我想創建一個簡單的矩陣,其中我將軟件需求的名稱作為索引,並將項目中的所有軟件測試用例作為列。

如果一個 SWRS 被一個 SWTS 覆蓋,我需要放置“某物”(例如一個十字架)。 在我的代碼草稿中,我創建了一個空數據框,然后迭代以放置十字架:

import pandas as pd
struct = {
            "swrslist":["swrs1","swrs2","swrs3","swrs4"],
            "swtslist":["swts1","swts2","swts3","swts4","swts5","swts6"],
            "mapping":
                {
                    "swrs1": ["swts1", "swts3", "swts4"],
                    "swrs2": ["swts2", "swts3", "swts5"],
                    "swrs4": ["swts1", "swts3", "swts5"]
                }
           }

if __name__ == "__main__":
    df = pd.DataFrame( index = pd.Index(pd.Series(struct["swrslist"])),
                      columns = pd.Index(struct["swtslist"]))
    print(df)
    for key in struct["mapping"].keys():
        for elem in struct["mapping"][key]:
            print(key, elem)
            df.at[key,elem] = "x"
    print(df)
    df.to_excel("mapping.xlsx")

輸出如下

      swts1 swts2 swts3 swts4 swts5 swts6
swrs1     x   NaN     x     x   NaN   NaN
swrs2   NaN     x     x   NaN     x   NaN
swrs3   NaN   NaN   NaN   NaN   NaN   NaN
swrs4     x   NaN     x   NaN     x   NaN

我知道創建一個空數據框然后迭代效率不高。 我嘗試按以下方式創建數據框

df = pd.DataFrame(struct["mapping"], index = pd.Index(pd.Series(struct["swrslist"])),
                      columns = pd.Index(struct["swtslist"]))

但它會創建一個空數據框:

      swts1 swts2 swts3 swts4 swts5 swts6
swrs1   NaN   NaN   NaN   NaN   NaN   NaN
swrs2   NaN   NaN   NaN   NaN   NaN   NaN
swrs3   NaN   NaN   NaN   NaN   NaN   NaN
swrs4   NaN   NaN   NaN   NaN   NaN   NaN

此外,如果 SWTS 是通過、失敗或未執行,我計划在未來提供不同的值。

如何有效地創建數據框,而不是迭代“映射”條目?

雖然我也使用了for循環,但是這個怎么樣?

df = pd.DataFrame(index=pd.Index(pd.Series(struct["swrslist"])), columns=pd.Index(struct["swtslist"]))
for key, value in struct["mapping"].items():
    df.loc[key, value] = "x"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM