python - 如何用唯一 ID 替换 Python Pandas 表文本值?

标签 python python-3.x pandas

我正在使用 Pandas 读取这种格式的文件:

fp = pandas.read_table("Measurements.txt")
fp.head()

"Aaron", 3, 5, 7  
"Aaron", 3, 6, 9  
"Aaron", 3, 6, 10 
"Brave", 4, 6, 0 
"Brave", 3, 6, 1

我想用唯一 ID 替换每个名称,因此输出如下所示:

"1", 3, 5, 7 
"1", 3, 6, 9 
"1", 3, 6, 10 
"2", 4, 6, 0 
"2", 3, 6, 1

我该怎么做?

谢谢!

最佳答案

我会使用 categorical数据类型:

In [97]: x['ID'] = x.name.astype('category').cat.rename_categories(range(1, x.name.nunique()+1))

In [98]: x
Out[98]:
    name  v1  v2  v3 ID
0  Aaron   3   5   7  1
1  Aaron   3   6   9  1
2  Aaron   3   6  10  1
3  Brave   4   6   0  2
4  Brave   3   6   1  2

如果您需要字符串 ID 而不是数字 ID,您可以使用:

x.name.astype('category').cat.rename_categories([str(x) for x in range(1,x.name.nunique()+1)])

或者,正如@MedAli 在 his answer 中提到的那样, 使用 factorize() 方法 - 演示:

In [141]: x['cat'] = pd.Categorical((pd.factorize(x.name)[0] + 1).astype(str))

In [142]: x
Out[142]:
    name  v1  v2  v3 ID cat
0  Aaron   3   5   7  1   1
1  Aaron   3   6   9  1   1
2  Aaron   3   6  10  1   1
3  Brave   4   6   0  2   2
4  Brave   3   6   1  2   2

In [143]: x.dtypes
Out[143]:
name      object
v1         int64
v2         int64
v3         int64
ID      category
cat     category
dtype: object

In [144]: x['cat'].cat.categories
Out[144]: Index(['1', '2'], dtype='object')

或将类别设为整数:

In [154]: x['cat'] = pd.Categorical((pd.factorize(x.name)[0] + 1))

In [155]: x
Out[155]:
    name  v1  v2  v3 ID cat
0  Aaron   3   5   7  1   1
1  Aaron   3   6   9  1   1
2  Aaron   3   6  10  1   1
3  Brave   4   6   0  2   2
4  Brave   3   6   1  2   2

In [156]: x['cat'].cat.categories
Out[156]: Int64Index([1, 2], dtype='int64')

解释:

In [99]: x.name.astype('category')
Out[99]:
0    Aaron
1    Aaron
2    Aaron
3    Brave
4    Brave
Name: name, dtype: category
Categories (2, object): [Aaron, Brave]

In [100]: x.name.astype('category').cat.categories
Out[100]: Index(['Aaron', 'Brave'], dtype='object')

In [101]: x.name.astype('category').cat.rename_categories([1,2])
Out[101]:
0    1
1    1
2    1
3    2
4    2
dtype: category
Categories (2, int64): [1, 2]

factorize() 方法的解释:

In [157]: (pd.factorize(x.name)[0] + 1)
Out[157]: array([1, 1, 1, 2, 2])

In [158]: pd.Categorical((pd.factorize(x.name)[0] + 1))
Out[158]:
[1, 1, 1, 2, 2]
Categories (2, int64): [1, 2]

关于python - 如何用唯一 ID 替换 Python Pandas 表文本值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38945840/

相关文章:

python - 高效地逐行读取Excel文件

python - 将 python 中的两个 pandas 数据框与公共(public)列和字符串条件合并

python - 如何将带有日期时间的 DataFrames 从 Stack Overflow 复制到 Python 中?

python - 使用 chmod +x python 将文件添加到 tar

python - 导入模块并使用其方法

python - django annotate - 条件计数

python - 如何在 python 3.2 中解压缩 c 结构?

python - 如何简化 if 语句中的多个 or 条件?

python - 是否可以在没有 Visual Studio 许可证的情况下在 Windows 上编译 Cython 模块用于商业目的?有哪些替代方案?

python - 创建对象并将用户定义的函数作为方法传递