首页 > 解决方案 > 如何使用 csv 和 pandas 制作产品代码列表?

问题描述

我是 pandas 的新手,我有一个 csv 文件,看起来像这样,但有 1.000 行:

     type       size    obs      code
0    inox       1        hard
1    inox       2        soft
2    inox       4        soft2
3    gold       4        hard
4    silver     1        hard
5    gold       2        hard

我想让代码识别谁是不锈钢,金和银,如果它是软的,硬的等,然后对不锈钢进行排序,对金进行排序。

   inox code 01 |
   gold code 02 |
   silver code 03 |
   hard 001 |
   soft 002 |
   soft2 003 |

我什至在stackoverflow上都没有在网上找到任何东西,我需要的出口:

        type       size     obs      code
   0    inox       1        hard     01.001.01
   1    inox       2        soft     01.002.02
   2    inox       4        soft2    01.003.03
   3    gold       4        hard     02.001.01
   4    gold       1        hard     02.001.02
   5    silver     2        soft     03.002.01

我可以使用 pandas.loc 吗?

标签: pythonpython-3.xpandascsv

解决方案


使用mapcumcount

  df['type'].map({'inox': '01', 'gold': '02', 'silver': '03'})  \
+ '.' \
+ df['obs'].map({'hard': '001', 'soft': '002', 'soft2': '003'}) \
+ '.0' \
+ df.groupby(['type']).cumcount().add(1).astype(str)

0    01.001.01
1    01.002.02
2    01.003.03
3    02.001.01
4    03.001.01
5    02.001.02
dtype: object

推荐阅读