python - 当 Na 存在时用等效字母替换矩阵中的所有数字

标签 python string pandas sequence

有一个巨大的矩阵,其元素是 1 到 15 范围内的数字。我想将矩阵转换为元素为字母的矩阵,使得 1 变为“a”,2 变为“b”,依此类推.最后我想合并每一行并创建一个序列。举个简单的例子:

import pandas as pd
import numpy as np, numpy.random
numpy.random.seed(1)
A = pd.DataFrame (np.random.randint(1,16,10).reshape(2,5)) 
A.iloc[1,4]= np.NAN
A
#   0   1   2   3   4
#0  6   12  13  9   10.0
#1  12  6   1   1   NaN

如果数据集中没有 Na,我将使用此代码:

pd.DataFrame(list(map(''.join, A.applymap(lambda n: chr(n + 96)).as_matrix())))

在这里,它给出了这个错误:

TypeError: ('integer argument expected, got float', 'occurred at index 4')

预期的输出是:

    0
0   flmij
1   lfaa

第一行应该有 5 个元素,第二行应该有 4 个元素。

最佳答案

使用if-else条件和sum:

df = pd.DataFrame(A.applymap(lambda n: chr(int(n) + 96) if pd.notnull(n) else '')
                   .values.sum(axis=1))
print (df)
       0
0  flmij
1   lfaa

详细信息:

print (A.applymap(lambda n: chr(int(n) + 96) if pd.notnull(n) else ''))
   0  1  2  3  4
0  f  l  m  i  j
1  l  f  a  a   

print (A.applymap(lambda n: chr(int(n) + 96) if pd.notnull(n) else '').values)
[['f' 'l' 'm' 'i' 'j']
 ['l' 'f' 'a' 'a' '']]

print (A.applymap(lambda n: chr(int(n) + 96) if pd.notnull(n) else '').values.sum(axis=1))
['flmij' 'lfaa']

另一种解决方案:

print (A.stack().astype(int).add(96).apply(chr).sum(level=0))
0    flmij
1     lfaa
dtype: object

详细信息:

reshape 为系列:

print (A.stack())
0  0     6.0
   1    12.0
   2    13.0
   3     9.0
   4    10.0
1  0    12.0
   1     6.0
   2     1.0
   3     1.0
dtype: float64

转换为整数:

print (A.stack().astype(int))
0  0     6
   1    12
   2    13
   3     9
   4    10
1  0    12
   1     6
   2     1
   3     1
dtype: int32

添加号码:

print (A.stack().astype(int).add(96))
0  0    102
   1    108
   2    109
   3    105
   4    106
1  0    108
   1    102
   2     97
   3     97
dtype: int32

转换为字母:

print (A.stack().astype(int).add(96).apply(chr))
0  0    f
   1    l
   2    m
   3    i
   4    j
1  0    l
   1    f
   2    a
   3    a
dtype: object

MultiIndex 第一级求和:

print (A.stack().astype(int).add(96).apply(chr).sum(level=0))
0    flmij
1     lfaa
dtype: object

关于python - 当 Na 存在时用等效字母替换矩阵中的所有数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50610739/

相关文章:

python - 对首次 sourceforge 项目贡献者的建议?

python - Scipy 不会找到最优值(简单的余弦函数)

c - C中的这个连接函数有什么问题?

python - 在Python中使用pandas数据框选择带有 bool 数组的行

python pandas - groupby.first() 返回 NaT 值

python - 根据在另一个 OptionMenu 中选择的内容更改 OptionMenu

python - 如何避免在 python 中作为参数传递时进行惰性属性评估

c++ - 控制台输出不断崩溃

python - 如何使用 Python 减少字符串中的重复字符

python - Pandas 根据其他列中的子字符串更改列值