joh*_*ith 6 python data-manipulation dataframe pandas
我有一个pandas数据帧,它有两列key和value,值总是由8位数字组成
>df1
key value
10 10000100
20 10000000
30 10100000
40 11110000
Run Code Online (Sandbox Code Playgroud)
现在我需要取值列并将其拆分为存在的数字,这样我的结果就是一个新的数据帧
>df_res
key 0 1 2 3 4 5 6 7
10 1 0 0 0 0 1 0 0
20 1 0 0 0 0 0 0 0
30 1 0 1 0 0 0 0 0
40 1 1 1 1 0 0 0 0
Run Code Online (Sandbox Code Playgroud)
我无法改变输入数据格式,我认为最传统的事情是将值转换为字符串并循环遍历每个数字字符并将其放入列表中,但是我正在寻找更优雅,更快速的东西,请帮忙.
编辑:输入不在字符串中,它是整数.
这应该工作:
df.value.astype(str).apply(list).apply(pd.Series).astype(int)
Run Code Online (Sandbox Code Playgroud)
一种方法可能是 -
arr = df.value.values.astype('S8')
df = pd.DataFrame(np.fromstring(arr, dtype=np.uint8).reshape(-1,8)-48)
Run Code Online (Sandbox Code Playgroud)
样本运行 -
In [58]: df
Out[58]:
key value
0 10 10000100
1 20 10000000
2 30 10100000
3 40 11110000
In [59]: arr = df.value.values.astype('S8')
In [60]: pd.DataFrame(np.fromstring(arr, dtype=np.uint8).reshape(-1,8)-48)
Out[60]:
0 1 2 3 4 5 6 7
0 1 0 0 0 0 1 0 0
1 1 0 0 0 0 0 0 0
2 1 0 1 0 0 0 0 0
3 1 1 1 1 0 0 0 0
Run Code Online (Sandbox Code Playgroud)