【问题标题】:Changing datatype as per column position in Python根据 Python 中的列位置更改数据类型
【发布时间】:2021-07-14 20:34:27
【问题描述】:

示例数据集:

data1 = {'Item': ['Bread', 'Milk', 'Rice', 'Wheat'], 'Price': [20.00, 21.00, 19.00, 18.00],'Unit':[34.3, 45.23,12.0,17.2]}   
country1 = pd.DataFrame(data1)

现在假设我有 5 个国家/地区的数据。对于所有国家,我想将价格和单位转换为整数。但是我想根据列位置而不是列名来转换它们(因为它们可以有本地语言的列名)。

请提出最好的方法。

附: - 我正在尝试使用以下代码获取一个数据帧

country1.columns[[1,2]] = country1.columns[[1,2]].astype(int)

并收到以下错误消息

TypeError: Index does not support mutable operations

【问题讨论】:

    标签: python position multiple-columns dtype


    【解决方案1】:

    尝试将列作为列表,然后使用列表中的索引来设置正确的列。

    data1 = {'Item': ['Bread', 'Milk', 'Rice', 'Wheat'], 'Price': [20.00, 21.00, 19.00, 18.00],'Unit':[34.3, 45.23,12.0,17.2]}
    country1 = pd.DataFrame(data1)
    
    cols = country1.columns.tolist()   # or just country1.columns
    
    country1[[cols[1], cols[2]]] = country1[[cols[1], cols[2]]].astype(int)
    

    得到

        Item  Price  Unit
    0  Bread     20    34
    1   Milk     21    45
    2   Rice     19    12
    3  Wheat     18    17
    

    【讨论】:

    • 感谢汉谟拉比,这很有帮助。
    【解决方案2】:

    您可以尝试这样的方法,使用列名来选择要更改的列。

    import pandas as pd
    
    data1 = {'Item': ['Bread', 'Milk', 'Rice', 'Wheat'], 'Price': [20.00, 
    21.00, 19.00, 18.00],'Unit':[34.3, 45.23,12.0,17.2]}
    country1 = pd.DataFrame(data1)
    country1 = country1.astype({'Price': int})
    

    如果您需要多个列,您可以在字典中为不同的列标题设置多个键。

    country1 = country1.astype({'Price': int})
    

    【讨论】:

    • 感谢您的回复卢卡斯,但是我不想按照列名来做。我有多个国家,每个国家可能有不同的列名,所以我必须更改所有不同国家的代码。取而代之的是,我正在尝试按照列位置进行操作。
    猜你喜欢
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    • 2018-05-14
    • 1970-01-01
    • 2016-06-08
    • 1970-01-01
    • 2019-04-29
    相关资源
    最近更新 更多