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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:24:06  来源:igfitidea点击:

pandas, convert DataFrame to MultiIndex'ed DataFrame

pythonpandasnumpymultidimensional-arraydataframe

提问by johnbaltis

I have a pandas.DataFramethat I want to convert to a MultiIndexed pandas.DataFrame.

我有一个pandas.DataFrame我想转换为MultiIndexed 的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 dfand want to turn it into df2(and don't have access to valsand result), how do I do this?

所以,我会从 IRL 开始df并想把它变成df2(并且无法访问valsresult),我该怎么做?

回答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 NaNto 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