【问题标题】:Add a new column to a dataframe from a Series or dictionary mapping my series index and a dataframe column to key pandas python从将我的系列索引和数据框列映射到关键熊猫 python 的系列或字典中向数据框添加新列
【发布时间】:2021-12-10 08:38:49
【问题描述】:

我遇到了这个问题,请帮忙:

我有一个数据框和一个系列如下:

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

Link to df

【问题讨论】:

    标签: python dataframe dictionary series


    【解决方案1】:

    您的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)
    

    【讨论】:

    • 谢谢!莫兹韦。是的,它实际上是来自 txt 文件的数据框,我使用过: df = pd.read_csv(r'frecuent_plane_failures.csv', header=0, index_col=False, sep=';') 。您的解决方案适用于我的示例,但不适用于我原来的问题,我得到 ValueError: The truth value of a DataFrame is ambiguous。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。如果我使用 df1['cause of failure'].map(s) 或 KeyError: '' 如果我使用 df1['cause of failure'].map(s['']),不知道如何将一个txt文件读入一个系列。我无法构建系列,因为我必须使用 txt 文件。有什么建议吗?
    • 那么请用可重现的问题示例澄清您的问题
    • 我已经将数据框转换为一个系列:s = df.T.iloc[0] 然后我按照你的建议使用了地图。谢谢,现在可以了!
    • @Sofia 太好了,很高兴它成功了,您可以考虑将问题标记为已解决;)
    猜你喜欢
    • 1970-01-01
    • 2017-03-06
    • 2015-06-23
    • 2019-09-28
    • 2018-02-26
    • 2021-05-18
    • 2016-09-12
    • 2018-05-08
    • 2020-06-03
    相关资源
    最近更新 更多