如何使用 pandas 或 numpy 将一列 6 个整数数字分成 6 列,每列 1 个数字?
进口熊猫作为 pd
将 numpy 导入为 np
Df = pd 系列 (范围 (123456,123465)
数据框 (df)
头 ()
号码
654321
223344
号码 | x1 | x2 | x3 | x4 | x5 | x6 |
654321 | 6 | 5 | 4 | 3 | 2 | 1 |
223344 | 2 | 3 | 4 |
这里有一个简单的建议:
进口熊猫作为 pd
# MCVE 数据框:
Df = pd.DataFrame ([123456 、 456789 、 135797 、 123 、 123456789],列 = [“数字”)
Def 数字 (x,n):
"返回以 10 为基数的整数的第 n 位""
返回 (x//10 * * n) % 10
Def 数字化 (df,key,n):
"从基数为 10 的整数中提取 n 个不太重要的数字""
对于范围 (n) 中的 i:
Df ['x % d' % i] = 数字 (df [键),n-i-1)
# 在 dataframe (inplace) 上应用函数:
数字化 (df,“数字”,6)
对于试用数据框,它返回:
号码 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 1 2 3
4 123456789 4 5 6 7 8 9
这种方法避免了强制转换的需要。string
and then cast again to int
。
它依赖于模整数运算,操作细节如下:
10 * * 3 # int: 1000 (整数幂)
54321//10 * * 3 # int: 54 (整数除法商)
(54321/10 * * 3) % 10 # int: 4 (整数除法的余数,模)
最后但并非最不重要的一点是,对于比n
digits or greater than (notice it returns the n
后一种情况下不太显著的数字)。
假设每个数字都有 6 位数字,这对视图来说很有趣:
U = df [[“数字”].To _ numpy ().Asttype (“u6”).view (“u”).Asttype (int)
Df.join (pd.DataFrame (u).重命名 (列 = lambda c: f 'x {c1}')
号码 x1 x2 x3 x4 x5 x6
0 654321 6 5 4 3 2 1
1 223344 2 2 3 3 4 4
你可以用np.unravel_index
Df = pd.DataFrame ({'number': [654321,223344]})
Def split_digits (df):
# 以 numpy 数组的形式获取数据
数字 = df ['number'].To _ numpy ()
# 提取数字
Digits = np.unravel_index (数字,6 * (10,))
# 创建列标题
列 = “123456” 中 i 的 ['数字' 、 * (f 'x {i}')]
# 新建并返回新的数据框
返回 pd.DataFrame (np.stack ([数字,* 位),轴 = 1),列 = 列,索引 = df.index)
拆分数字 (df)
# 号码 x1 x2 x3 x4 x5 x6
#0 654321 6 5 4 3 2 1
#1 223344 2 2 3 3 4 4
Timeit (波长: split_digits (df),数量 = 1000)
0.3550272472202778
谢谢 @ GZ0 段pandas
小费。
此外,包括一个zfill
以防并非所有数字都是 6 位数字
Df.Number 中 x 的 dat = [列表 (map (int,str (x).zfill (6)]
D = pd.DataFrame (dat,df.index).重命名 (列 = lambda x: f 'x {x 1}')
加入 (d)
号码 x1 x2 x3 x4 x5 x6
0 654321 6 5 4 3 2 1
1 223344 2 2 3 3 4 4
这就是数字
Df.Number 中 x 的 dat = [列表 (map (int,str (x).zfill (6)]
Dat
【【 6 、 5 、 4 、 3 、 2 、 1 】、【 2 、 3 、 4 】】
这将创建一个索引与df
AND renames the columns to have an 'x'
in front and begin with 'x1'
and not 'x0'
D = pd.DataFrame (dat,df.index).重命名 (列 = lambda x: f 'x {x 1}')
D.
X1 x2 x3 x4 x5 x6
0 6 5 4 3 2 1
1 2 2 3 3 4 4
虽然基于字符串的解决方案更简单,在大多数情况下可能足够好,但是你可以用数学来做到这一点,如果你有一个大数据集,数学可以在速度上产生显著
将 numpy 导入为 np
进口熊猫作为 pd
Df = pd.DataFrame ({'number': [654321,223344]})
Num_cols = int (np.log10 (df ['number').max ()-1)) + 1
Vals = (df ['number']。值 [:,np.newaxis]//(10 * * np.arange
Df_digits = pd.DataFrame (vals,columns = 范围内 i 的 [f 'x {i + 1}')
轴 = 1) df2 = pd.concat ([df,df_digits])
打印 (df2)
# 号码 x1 x2 x3 x4 x5 x6
#0 654321 6 5 4 3 2 1
#1 223344 2 2 3 3 4 4
假设所有的数字都是相同的长度 (有相同的位数),我会按照以下方式使用numpy
:
将 numpy 导入为 np
A = np.数组 ([[654321],[223344]])
Str_a = a.Asttype (str)
Out = np.Apply_along_ axis (lambda x: list (x [0)),1,str_a)
打印 (输出)
输出:
[['6' '5' '4' '3' '2' '1']
【 '2' '2' '3' '3' '4' '4']]
请注意out
is currently np.array
of str
s, you might convert it to int
如果出现这种需求。
我真的很喜欢 @ user3483203 的回答。我觉得.str.findall
可以使用任意数量的数字:
数据框 ({)
“号码”: [65432178888,22334474343]
})
U = df ['number'].Asttype (str).str.findall (r '(\ w)')
Df.join (pd.DataFrame (列表 (u)).重命名 (列 = lambda c: f 'x {c1}').应用
号码 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11
0 65432178888 6 5 4 3 2 1 7 8
1 22334474343 2 3 3 4 4 7 4 3
简单的方法:
> Df
号码
0 123456
456789
2 135797
先把列转换成字符串
> Df ['number'] = df ['number']。
使用字符串索引创建新列
> Df ['x1'] = df ['number'].str [0]
> Df ['x2'] = df ['number'].str [1]
> Df ['x3'] = df ['number'].str [2]
> Df ['x4'] = df ['number'].str [3]
> Df ['x5'] = df ['number'].str [4]
> Df ['x6'] = df ['number'].str [5]
> Df
号码 x1 x2 x3 x4 x5 x6
0 123456 1 2 3 4 5 6
1 456789 4 5 6 7 8 9
2 135797 1 3 5 7 9 7
> Df.drop (“number”,轴 = 1,inplace = True)
> Df
X1 x2 x3 x4 x5 x6
0 1 2 3 4 5 6
1 4 5 6 7 8 9
2 1 3 5 7 9 7
@ 另一招str.split()
> Df = df ['number']。 str. 拆分 ('(\ d {1})',展开 = True)。 add _ 前缀 ('x')。 drop (列 = ['xd' 、 'x2' 、 'x4' 、 'x6' 、 'x8' 、 'x10' 、 'x12')
> Df
X1 x3 x5 x7 x9 x11
0 1 2 3 4 5 6
1 4 5 6 7 8 9
2 1 3 5 7 9 7
> Df.重命名 (列 = {'x3': 'x2','x2': 'x3','x7': 'x4','x9':'
X1 x2 x3 x4 x5 x6
0 1 2 3 4 5 6
1 4 5 6 7 8 9
2 1 3 5 7 9 7
> Df = df ['number']。 str. 拆分 (r '(\ d {1})',展开 = True)。 t. 替换 ('',np。南)。 dropna ()。 T
> Df
1 3 5 7 9 11
0 1 2 3 4 5 6
1 4 5 6 7 8 9
2 1 3 5 7 9 7
> Df.重命名 (列 = {1: 'x1',3: 'x2',5: 'x3',7: 'x4',9: 'x5',
X1 x2 x3 x4 x5 x6
0 1 2 3 4 5 6
1 4 5 6 7 8 9
2 1 3 5 7 9 7