我為我的資料框預定義了標題。但我們收到的資料可能包括也可能不包括所有列。但是我們的輸出檔案應該包含標題中的所有欄位。如果輸入檔案中沒有資料,則將其保留為空白,否則填充值。
input file 1:
ID Name Address Shippment
1 john address1 Y
2 Jessy address2 N
input file2
ID Name Address Shippment Delivered
1 john address1 Y Y
2 Jessy address2 N N
headers=['ID','Name','Address','Shippment','Delivered']
output file 1:
ID Name Address Shippment Delivered
1 john address1 Y
2 Jessy address2 N
output file 1:
ID Name Address Shippment Delivered
1 john address1 Y Y
2 Jessy address2 N N
當標題是隨機的時,如何將標題映射到 soruce 檔案?
我嘗試使用 zip 和 update 但這會查看索引和地圖。源列可以是隨機的,它必須與標題中的欄位順序相匹配。
for i,index in zip(header,df):
final.update({i: df[index].tolist()})
df_final= pd.DataFrame(final)
我怎樣才能做到這一點?
uj5u.com熱心網友回復:
您可以使用reindex()來確保包含所有預定義的標頭。資料中任何缺失的列都將用 NaN 填充:
headers = ['ID','Name','Address','Shippment','Delivered']
df = df.reindex(columns=headers)
輸入
ID Name Address Shippment
0 1 john address1 Y
1 2 jessy address2 N
輸出
ID Name Address Shippment Delivered
0 1 john address1 Y NaN
1 2 jessy address2 N NaN
如果輸入中的列不在預定義的序列中,reindex()也將修復該問題:
輸入
ID Address Name Shippment
0 1 address1 john Y
1 2 address2 jessy N
輸出
ID Name Address Shippment Delivered
0 1 john address1 Y NaN
1 2 jessy address2 N NaN
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/488321.html
