pandas 熊猫,将 DataFrame 转换为 MultiIndex'ed DataFrame
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40507505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pandas, convert DataFrame to MultiIndex'ed DataFrame
提问by johnbaltis
I have a pandas.DataFrame
that I want to convert to a MultiIndex
ed pandas.DataFrame
.
我有一个pandas.DataFrame
我想转换为MultiIndex
ed 的pandas.DataFrame
。
import numpy
import pandas
import itertools
xs = numpy.linspace(0, 10, 100)
ys = numpy.linspace(0, 0.1, 20)
zs = numpy.linspace(0, 5, 200)
def func(x, y, z):
return x * y / z
vals = list(itertools.product(xs, ys, zs))
result = [func(x, y, z) for x, y, z in vals]
# Original DataFrame.
df = pandas.DataFrame(vals, columns=['x', 'y', 'z'])
df = pandas.concat((pandas.DataFrame(result, columns=['result']), df), axis=1)
# I want to turn `df` into this `df2`.
index = pandas.MultiIndex.from_tuples(vals, names=['x', 'y', 'z'])
df2 = pandas.DataFrame(result, columns=['result'], index=index)
Note that in this example I create what I wantand what I have.
请注意,在此示例中,我创建了我想要的和我拥有的.
So, IRL I would start with df
and want to turn it into df2
(and don't have access to vals
and result
), how do I do this?
所以,我会从 IRL 开始df
并想把它变成df2
(并且无法访问vals
和result
),我该怎么做?
回答by jezrael
You need set_index
:
你需要set_index
:
print (df2.head())
result
x y z
0.0 0.0 0.000000 NaN
0.025126 0.0
0.050251 0.0
0.075377 0.0
0.100503 0.0
print (df.set_index(['x','y','z']).head())
result
x y z
0.0 0.0 0.000000 NaN
0.025126 0.0
0.050251 0.0
0.075377 0.0
0.100503 0.0
If need compare both DataFrames
, need replace NaN
to same values, else get False
:
如果需要比较两者DataFrames
,需要替换NaN
为相同的值,否则得到False
:
print (df.set_index(['x','y','z']).eq(df2).all())
result False
dtype: bool
print (np.nan == np.nan)
False
print (df.fillna(1).set_index(['x','y','z']).eq(df2.fillna(1)).all())
result True
dtype: bool