【问题标题】:Creating column with datatypes with pandas使用熊猫创建具有数据类型的列
【发布时间】:2019-03-18 15:56:17
【问题描述】:

我有一个 DataFrame df:

A   B
1   dog 
cat XX 

我一直在尝试创建一个看起来像这样的 pandas DataFrame df_new:

A   B    type_of_A   type_of_B
1   dog  int         string
cat XX   string      whateverdtype it may be

我试过了:

df_new["type_of_A"] = [pd.api.types.infer_dtype(i) for i in range(df_new['A'].values)]

但我只得到:

TypeError:只有整数标量数组可以转换为标量 索引

谁能给我一个提示?这是正确的方法吗?

提前非常感谢

【问题讨论】:

    标签: python-3.x pandas for-loop types multiple-columns


    【解决方案1】:

    使用applymaptype,返回concat

    s=df.applymap(type).add_prefix('type_of_')
    df=pd.concat([df,s],1)
    Out[543]: 
         A    B      type_of_A      type_of_B
    0    1  dog  <class 'int'>  <class 'str'>
    1  cat   XX  <class 'str'>  <class 'str'>
    

    【讨论】:

    • 有没有办法将此过程应用于单个列而不是整个 df?因为我相信“applymap”不适用于系列。
    • @iraciv94 只需为系列执行 s.apply(type)
    猜你喜欢
    • 1970-01-01
    • 2019-09-29
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    • 2017-01-15
    • 1970-01-01
    • 1970-01-01
    • 2020-03-02
    相关资源
    最近更新 更多