【问题标题】:How to convert to a list after using pandas [duplicate]使用熊猫后如何转换为列表[重复]
【发布时间】:2020-05-25 00:08:56
【问题描述】:

这是我使用 pandas 生成的 .csv 文件。我想将“年龄”和“学习”列转换回列表类型。但是'''dp.types'''显示年龄的类型是'''object'''。所有元素都是字符串,'[' '6' '8' ,'8' '3' ']'。有谁知道如何用整数 [68,83] 转换回普通列表 [在此输入图片描述]1

【问题讨论】:

    标签: python pandas numpy dataframe computer-science


    【解决方案1】:

    要将 pandas 中的列转换为列表,请使用:

    # assuming df is your dataframe
    df["column name"].to_numpy().to_list()
    

    首先将其转换为 numpy 数组,然后将 numpy 数组(其中只有数字)转换为列表 或者将整列转换为数值数据类型,然后转换为列表:

    pd.to_numeric(df["column name"]).to_list()
    

    【讨论】:

    • 为什么是to_numpy
    • 我在某处读到.to_list() 可能会尝试将其转换为字符串。首先转换为 numpy 向我们保证它将是数字
    • 只要使用astype
    猜你喜欢
    • 2019-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-25
    • 2017-04-08
    • 2019-10-12
    • 2019-02-25
    • 2019-08-04
    相关资源
    最近更新 更多