python - 将六位数字列拆分为一位数的分隔列

标签 python pandas numpy

我如何使用 Pandas 或 numpy 将一列 6 个整数数字分成 6 列,每列一个数字?

import pandas as pd
import numpy as np

df = pd.Series(range(123456,123465))

df = pd.DataFrame(df)


df.head()

我拥有的是下面这个
Number
654321
223344

期望的结果应该如下所示。
Number | x1 | x2 | x3 | x4 | x5 | x6 |
654321 |  6 |  5 | 4  |  3 |  2 |  1 |
223344 |  2 |  2 | 3  |  3 |  4 |  4 |

最佳答案

MCVE

这是一个简单的建议:

import pandas as pd

# MCVE dataframe:
df = pd.DataFrame([123456, 456789, 135797, 123, 123456789], columns=['number'])

def digit(x, n):
    """Return the n-th digit of integer in base 10"""
    return (x // 10**n) % 10

def digitize(df, key, n):
    """Extract n less significant digits from an integer in base 10"""
    for i in range(n):
        df['x%d' % i] = digit(df[key], n-i-1)

# Apply function on dataframe (inplace):
digitize(df, 'number', 6)

对于试验数据帧,它返回:
      number  x0  x1  x2  x3  x4  x5
0     123456   1   2   3   4   5   6
1     456789   4   5   6   7   8   9
2     135797   1   3   5   7   9   7
3        123   0   0   0   1   2   3
4  123456789   4   5   6   7   8   9

观察

此方法避免了转换为 string 然后再次转换为 int 的需要。

它依赖于模整数算法,操作细节如下:
10**3                  # int: 1000 (integer power)
54321 // 10**3         # int: 54   (quotient of integer division)
(54321 // 10**3) % 10  # int: 4    (remainder of integer division, modulo)

最后但并非最不重要的一点是,它对于小于 n 位数或大于 n 位数的数字是安全且准确的(注意它在后一种情况下返回 ojit_code 较低有效位数)。

关于python - 将六位数字列拆分为一位数的分隔列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57792952/

相关文章:

python - Python 中的夏令时

python - 如何将数据写入 Redshift,这是在 Python 中创建的数据框的结果?

python - Keras Lambda 层的内存泄漏

python - PyCharm 显示没有来自 pandas 的输出

python - Numpy 将数组乘以矩阵(外积)

python - numpy数组维度不匹配错误

python - VS Code 在 Python 代码执行期间不会打印,只会在最后打印

python - Pandas 提取多字符正则表达式

python - 在 pandas 中使用 matplotlib 绘制散点图时如何将标记与线连接起来

python - numpy 中结构化数组的 ndim?