在Python中分开的膨胀元组的好方法
给定两个变量的元组('a','e1_g1')
,我想将其扩展到三个变量的元组中
。
以下代码应回答目标
import numpy as np
import pandas as pd
np.random.seed(0)
arr = np.random.randint(5, size=(2, 9))
_names = ['a','a','a','a','a','a','a','a','a']
_idx = ['E1_g1','E1_g2','E1_g3',
'E2_g1','E2_g2','E2_g3',
'E3_g1','E3_g2','E3_g3']
columns = pd.MultiIndex.from_arrays([_names, _idx])
df= pd.DataFrame(data=arr, columns=columns)
ntuple=[]
for dg in df.columns:
A,B=dg
f,r=B.split('_')
ntuple.append((A,f,r))
# df.colums=pd.MultiIndex.from_arrays(ntuple) # WIP since I still got an error here
,但是,我想知道是否有另一种方法,也许可以改进,尤其是for-loops
中的步骤。
Given a tuple of two variable ('a','E1_g1')
, I would like to expand it into tuple of three variable ('a','E1', 'g1')
.
The following code should answer the objective
import numpy as np
import pandas as pd
np.random.seed(0)
arr = np.random.randint(5, size=(2, 9))
_names = ['a','a','a','a','a','a','a','a','a']
_idx = ['E1_g1','E1_g2','E1_g3',
'E2_g1','E2_g2','E2_g3',
'E3_g1','E3_g2','E3_g3']
columns = pd.MultiIndex.from_arrays([_names, _idx])
df= pd.DataFrame(data=arr, columns=columns)
ntuple=[]
for dg in df.columns:
A,B=dg
f,r=B.split('_')
ntuple.append((A,f,r))
# df.colums=pd.MultiIndex.from_arrays(ntuple) # WIP since I still got an error here
But, I wonder whether there is another way, that perhaps can be improve especially the step within the for-loops
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(2)
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
不是最干净的,但这是我能够做的:
输出:
但是,由于
dtype
是对象,因此您的确无法更快。实际上,简单的理解速度更快:性能:
唯一真正的好处是第一个示例中语法的相对简单性。
Not the cleanest, but this is what I was able to do:
Output:
However, since the
dtype
is object, you really can't get much faster. In fact, a plain comprehension is a bit faster:Performance:
The only real benefit is the relative simplicity of the syntax in the first example.