我有以下具有特定列數的資料框。
id column1 column2 column3 column4
0 X A P S
1 Y
2 Z
用戶必須通過 .txt 檔案提供輸入,該檔案包含必須添加到當前資料幀的新列的引數。.txt 檔案具有以下內容。
{
"new_case": {
"N": 2,
"concept:name": [
"column1",
"column3",
"column4"
]
}
}
資料框中的新列應包含 .txt 檔案中提到的列中的值。
預期輸出。
id column1 column2 column3 column4 new_column
0 X A P S X P S
1 Y Y Nan Nan
2 Z Z Nan Nan
任何幫助表示贊賞:) 謝謝。
uj5u.com熱心網友回復:
只是你的示例資料的一個例子
import json
import pandas as pd
with open('input.txt', 'r', encoding='utf-8') as f:
data = json.loads(f.read())
df['new_column'] = df[data['new_case']['concept:name']].fillna('Nan').agg(' '.join, axis=1)
print(df)
id column1 column2 column3 column4 new_column
0 0 X A P S X P S
1 1 Y <NA> <NA> <NA> Y Nan Nan
2 2 Z <NA> <NA> <NA> Z Nan Nan
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/459198.html
上一篇:如何在變數結果后命名資料框索引?
下一篇:基于測驗集中資料組的線性回歸預測
