我想使用字典根據輸入資料集的列創建元資料變數。具體來說,我希望元資料變數具有完全這樣的結構和值:
metadata = {
'fields': {
'id': {'type': 'categorical'},
'name': {'type': 'categorical'},
'category_id': {'type': 'categorical'},
'category_label': {'type': 'categorical'},
'Compatible operating systems.2507': {'type': 'categorical'},
'Compatible operating systems.2507.unit': {'type': 'categorical'},
'Dimensions (WxDxH).49': {'type': 'categorical'},
'Dimensions (WxDxH).49.unit': {'type': 'categorical'},
'Internal mass storage.588': {'type': 'categorical'},
'Internal mass storage.588.unit': {'type': 'categorical'},
'Processor cores.6089': {'type': 'categorical'},
'Processor cores.6089.unit': {'type': 'categorical'},
'Built-in processor.7787': {'type': 'boolean'},
'Built-in processor.7787.unit': {'type': 'categorical'}
},
'constraints': [],
'primary_key': 'id'
}
我創建上述元資料結構的輸入資料框如下所示:

到目前為止,我已嘗試使用以下代碼來執行此操作:
metadata = {}
metadata['fields'] = {}
for col_name in table_dtypes['index']:
metadata['fields'][col_name] = {}
上面的代碼輸出如下:

如您所見,我的值是 {}。我想用'type'作為鍵填充它們,關聯的值將是我的螢屏截圖資料框中的列“0”(即物件,布林值)。我希望這是一個自動回圈程序,因為將來除了“分類”之外,我還將擁有“浮點”、“整數”和其他資料型別。
我該怎么做呢?
更新:
series_structure = pd.Series()
for i in table_dtypes[0]:
if i == "object":
type_dict = {'type': 'categorical'}
series_structure.append(type_dict)
elif i == "boolean":
type_dict = {'type': 'boolean'}
series_structure.append(type_dict)
elif i == "datetime64": # revisit here
type_dict = {'type': 'datetime', 'format': '%Y-%m-%d'}
series_structure.append(type_dict)
elif i == "int64":
type_dict = {'type': 'id', 'subtype': 'integer'}
series_structure.append(type_dict)
elif i == "float64": # revisit here
type_dict = {'type': 'numerical', 'subtype': 'float'}
series_structure.append(type_dict, ignore_index=ignore_index, verify_integrity=verify_integrity)
錯誤:
TypeError: cannot concatenate object of type '<class 'dict'>'; only Series and DataFrame objs are valid
uj5u.com熱心網友回復:
您可以將0列轉換為 dicts 陣列,replace用于替換'object'('categorical'以及您可能需要的任何其他內容)),然后應用一個函式來回傳一個 dicttype作為鍵和該值。zip然后,您可以將其index轉換為列并轉換為欄位字典。最后,您可以將其添加到具有constraintsandprimary_id屬性的輸出字典中。
types = df['0'].replace({ 'object' : 'categorical' }).apply(lambda x:{ 'type' : x })
fields = dict(zip(df['index'], types))
metadata = { 'fields' : fields,
'constraints': [],
'primary_key': df.loc[0, 'index']
}
注意我假設primary_key存盤在 的第一行index,如果不是這樣,您可以根據需要進行調整。
對于此示例輸入:
index 0
0 id object
1 name object
2 category_id object
3 category_label object
4 Built-in processor.7787 boolean
5 A float float
6 An integer int
您將獲得以下輸出(為了便于閱讀,轉儲為 JSON):
{
"fields": {
"id": {
"type": "categorical"
},
"name": {
"type": "categorical"
},
"category_id": {
"type": "categorical"
},
"category_label": {
"type": "categorical"
},
"Built-in processor.7787": {
"type": "boolean"
},
"A float": {
"type": "float"
},
"An integer": {
"type": "int"
}
},
"constraints": [],
"primary_key": "id"
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/523809.html
