python - 将 Pandas 系列转换为整数

标签 python pandas

给定这样一个数据框:

'John', 0.25
'Mary', 0.2
'Adam', 0.1
'Andrew', 0.6

我想为特定系列中的每个类别生成一个唯一的整数。例如,在上面的例子中,输出可能是这样的

0, 0.25
1, 0.2
2, 0.1
3, 0.6

可能仅适用于 pandas 或标准库。

最佳答案

我想你可以使用 factorize喜欢:

print df
          a     b
0    'John'  0.25
1    'Mary'  0.20
2    'Mary'  0.20
3    'Adam'  0.10
4    'Adam'  0.10
5    'Adam'  0.10
6  'Andrew'  0.60

print pd.factorize(df.a)
(array([0, 1, 1, 2, 2, 2, 3]), 
 Index([u''John'', u''Mary'', u''Adam'', u''Andrew''], dtype='object'))

df['a'] = pd.factorize(df.a)[0]
print df

   a     b
0  0  0.25
1  1  0.20
2  1  0.20
3  2  0.10
4  2  0.10
5  2  0.10
6  3  0.60

关于python - 将 Pandas 系列转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35751724/

相关文章:

python - 如何对数据框行进行分组并过滤字符串列表中的所有事件?

python - 如何将 .sav 文件转换为 csv 文件

python - 文件较大时 CSV 文件出现问题

python - Ansible EC2 Python 错误 : ValueError: No JSON object could be decoded

python - 为什么mysql connector break ("Lost connection to MySQL server during query"错误)

python - 在 Pyramid 关闭时运行代码

python - Pandas 数据框 : how to aggregate a subset of rows based on value of a column

pandas - 如何将 bool 值的数据帧转换为 1 和 np.NaN 的数据帧?

python - (pandas json_normalize) 嵌套 Json

python - 使用关键字提取在 Pandas 中动态创建列