【问题标题】:How to replace numerical values from a csv with categorical values using python [closed]如何使用python将csv中的数值替换为分类值[关闭]
【发布时间】:2018-06-04 18:32:42
【问题描述】:

我的问题是关于使用python将csv文件中的数值替换为字符串。目的是计算CDF(累积分布函数)。

数据集名称为'hsb',类标签为'status',共有304行数值数据1s和2s。我想将 1 替换为“正”,将 2 替换为“负”。

【问题讨论】:

  • 您编写的代码读取数据,根据需要对其进行转换,然后将其作为文件写回。 SO 是关于修复 your 代码 - 而不是编写您的代码。请再次查看how to askon-topic,如果您有任何问题,请提供您的代码minimal verifyable complete example

标签: python python-3.x pandas cdf


【解决方案1】:

考虑下面的例子,它使用.map() 映射字典中的值。

 df = pd.DataFrame({
    'col':[1,1,2,2,2,1]
})

输出:

   col
0   1
1   1
2   2
3   2
4   2
5   1

现在,

df['col'] = df['col'].map({1:'positive', 2:'negative'})

输出:

       col
0   positive
1   positive
2   negative
3   negative
4   negative
5   positive

【讨论】:

    猜你喜欢
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-23
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    • 2020-08-23
    相关资源
    最近更新 更多