在多索引框架上调用df.sort_index()
时,如何将func_2
用于级别two
?
func_1 = lambda s: s.str.lower()
func_2 = lambda x: np.abs(x)
m_sorted = df_multi.sort_index(level=['one', 'two'], key=func_1)
documentation是"For MultiIndex inputs, the key is applied per level",这是模糊的.
import pandas as pd
import numpy as np
np.random.seed(3)
# Create multiIndex
choice = lambda a, n: np.random.choice(a, n, replace=True)
df_multi = pd.DataFrame({
'one': pd.Series(choice(['a', 'B', 'c'], 8)),
'two': pd.Series(choice([1, -2, 3], 8)),
'A': pd.Series(choice([2,6,9,7] ,8))
})
df_multi = df_multi.set_index(['one', 'two'])
# Sort MultiIndex
func_1 = lambda s: s.str.lower()
func_2 = lambda x: np.abs(x)
m_sorted = df_multi.sort_index(level=['one'], key=func_1)