簡體   English   中英

python - 如何為數據框分配特殊索引?

[英]python - how to assign a special index to the data frame?

我有以下數據框:

Col1    Col2      Col3   
X       Apple      A 
Y       Orange     B
Y       Apple      B
X       Apple      B
X       Orange     B

我想創建一個 4 位數字來創建索引 邏輯是當 Col1 和 Col2 匹配時,4 位數字將與之前相同。 索引是通過結合 Number 和 Col3 創建的

Expected output
Number  Col1    Col2      Col3   Index
0001    X       Apple      A     0001-A
0002    Y       Orange     B     0002-B 
0003    Y       Apple      B     0003-B
0001    X       Apple      B     0001-B
0004    X       Orange     B     0004-B

我怎樣才能做到這一點?

首先為索引的數字部分制作一個字典,使用第 1 列和第 2 列的連接,然后您就有了所有行的索引的數字部分,因此只需將索引與第 3 列連接起來。

獲取索引號的函數:

def get_index_number(row,index_dict):
   unique_name=row['col1']+"-"+row['col2']
   if unique_name not in index_dict:
      index_dict[unique_name]=row['number']
   return index_dict[unique_name]

用法:假設您在數據框中已經有“索引”列(如果沒有添加)

index_dict={}
for row in dataframe.iterrows():
   row['index']=get_index_number(row,index_dict)

暫無
暫無

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

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