Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Pandas 多索引级别中的Partition.diff()_Pandas_Multi Index - Fatal编程技术网

Pandas 多索引级别中的Partition.diff()

Pandas 多索引级别中的Partition.diff(),pandas,multi-index,Pandas,Multi Index,我的问题涉及在多索引级别的分区内调用.diff() 在下面的示例中,第一个 df.diff()是 但我希望它是: values Greek English alpha a NaN b 2 c 2 d 2 beta e NaN f 1 g

我的问题涉及在多索引级别的分区内调用.diff()

在下面的示例中,第一个

df.diff()是

但我希望它是:

               values
Greek English        
alpha a           NaN
      b             2
      c             2
      d             2
beta  e            NaN
      f             1
      g             1
      h             1
这里有一个解决方案,使用循环,但我认为我可以避免循环

import pandas as pd
import numpy as np

df = pd.DataFrame({'values' : [1.,3.,5.,7.,18.,19.,20.,21.],
   'Greek' : ['alpha', 'alpha', 'alpha', 'alpha','beta','beta','beta','beta'],
   'English' : ['a', 'b', 'c', 'd','e','f','g','h']})

df.set_index(['Greek','English'],inplace =True)
print df

# (1.) This is not the type of .diff() i want.
# I need it to respect the level='Greek' and restart   
print df.diff()


# this is one way to achieve my desired result but i have to think
# there is a way that does not involve the need to loop.
idx = pd.IndexSlice
for greek_letter in df.index.get_level_values('Greek').unique():
    df.loc[idx[greek_letter,:]]['values'] = df.loc[idx[greek_letter,:]].diff()

print df
如果您愿意,只需按
level=0
或“希腊语”即可,然后您可以调用值:

In [179]:

df.groupby(level=0)['values'].diff()
Out[179]:
Greek  English
alpha  a         NaN
       b           2
       c           2
       d           2
beta   e         NaN
       f           1
       g           1
       h           1
dtype: float64
In [179]:

df.groupby(level=0)['values'].diff()
Out[179]:
Greek  English
alpha  a         NaN
       b           2
       c           2
       d           2
beta   e         NaN
       f           1
       g           1
       h           1
dtype: float64