簡體   English   中英

從系列或字典向數據幀添加一個新列,將我的系列索引和數據幀列映射到鍵熊貓 python

[英]Add a new column to a dataframe from a Series or dictionary mapping my series index and a dataframe column to key pandas python

我被這個問題困住了,請幫忙:

我有一個數據框和一個系列如下:

import pandas as pd

df1 = pd.DataFrame({"ID": [4,8,35,28,34,34,14,28], 
                    "cause of failure": [5,3,0,1,7,8,6,7], 
                    "crash": [0,0,0,1,1,1,1,1]}) 

我有一個系列:

s = pd.DataFrame({'':["None","Design flaw","metal fatigue","Manufacturing flaw","Pilot 
                 error","Mechanical failure","Improper maintenance","Fire","Corrosion"]})

#要添加新列,我編寫了 add_column 函數,在函數內部,我將 s1 轉換為 #a 字典,但是

def add_column(df,s, ref_column, new_column):
    dict_s = s.to_dict(orient='dict')
    #dict_s = s.loc[0:].to_dict(orient='index')
    error', 5: 'Mechanical failure', 6: 'Improper maintenance', 7: 'Fire', 8: 'Corrosion'}
    df[new_column] = df[ref_column].map(dict_s)
    return df

add_column(df1,s1,"failure code","failure")

#我不希望空頭進入字典,只是系列的鍵值對

{'': {0: 'None', 1: 'Design flaw', 2: 'metal fatigue', 3: 'Manufacturing flaw', 4: 'Pilot error', 5: 'Mechanical failure', 6: 'Improper maintenance', 7: 'Fire', 8: 'Corrosion'}}

#Like this:
{0: 'None', 1: 'Design flaw', 2: 'metal fatigue', 3: 'Manufacturing flaw', 4: 'Pilot error', 5: 'Mechanical failure', 6: 'Improper maintenance', 7: 'Fire', 8: 'Corrosion'}

我不能把字典弄對

#然后我想映射這個字典以匹配“失敗代碼”列中的代碼並將它們添加為新列“失敗”最后我想向 df1 數據幀添加一個新列失敗。

結果應如下所示:

    ID  failure code    crash   failure
1   8   3   0   Manufacturing flaw
2   35  0   0   None
3   28  1   1   Design flaw
4   34  7   1   Fire
5   34  8   1   Corrosion
6   14  6   1   Improper maintenance
7   28  7   1   Fire

鏈接到 df

你的s不是一個系列,而是一個數據幀。 map使用系列:

df1['new_column'] = df1['cause of failure'].map(s[''])

輸出:

   ID  cause of failure  crash            new_column
0   4                 5      0    Mechanical failure
1   8                 3      0    Manufacturing flaw
2  35                 0      0                  None
3  28                 1      1           Design flaw
4  34                 7      1                  Fire
5  34                 8      1             Corrosion
6  14                 6      1  Improper maintenance
7  28                 7      1                  Fire

或直接構建一個系列:

s = pd.Series(["None","Design flaw","metal fatigue","Manufacturing flaw","Pilot error","Mechanical failure","Improper maintenance","Fire","Corrosion"])

df1['new_column'] = df1['cause of failure'].map(s)

暫無
暫無

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

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