代码之家  ›  专栏  ›  技术社区  ›  Amrith Krishna

将包含元组的pandas列转换为字符串

  •  0
  • Amrith Krishna  · 技术社区  · 5 年前

    df 共800行,其中一列包含元组:

            conComb     insOrDel    supp
    580     ('r', '>', 'ins')   36272   0.199807
    449     ('ar', '>', 'ins')  31596   0.174049
    594     ('tar', '>', 'ins')     4398    0.024227
    529     ('lar', '>', 'ins')     3037    0.016730
    

    df.dtypes

    conComb      object
    insOrDel      int64
    supp        float64
    dtype: object
    

    我想转换 conComb

    df["conComb"] = df["conComb"].astype(str)

    df["conComb"] = df["conComb"].astype(|S1)

    df["conComb"] = df["conComb"].values.astype(str) ,

    列的类型 炮灰 改成字符串?

    对评论中讨论的问题的扩展

    confDF 24000行

    conComb     objF    insOrDel
    0   ('<ablucar', '>', 'ins')    (a)     11
    1   ('<ablucar', '>', 'ins')    (ai)    3
    2   ('<ablucar', '>', 'ins')    (ais)   3
    3   ('<ablucar', '>', 'ins')    (amos)  2
    

    数据框 引发以下消息 ValueError: You are trying to merge on object and int64 columns. If you wish to proceed you should use pd.concat

    confDF["conComb"] = confDF["conComb"].astype(str)
    pd.DataFrame.join(df,confDF, on ="conComb")
    

    怎么能背诵出来?

    1 回复  |  直到 5 年前
        1
  •  2
  •   jezrael    5 年前

    我认为两者之间有区别 dtype s和 type

    string s, dict s, tuple s和 list s具有相同的数据类型 object .

    核对 dtypes 使用:

    print (df.dtypes)
    

    对于支票类型,请使用:

    print (df.iloc[0].apply(type))
    

    join 默认情况下使用索引值和列(如果指定) on 参数。

    confDF["conComb"] = confDF["conComb"].astype(str)
    df1 = pd.merge(df,confDF, on ="conComb", how='left')
    

    或:

    confDF["conComb"] = confDF["conComb"].astype(str)
    df1 = df.set_index('conComb').join(confDF, on ="conComb")