pandas 对分组数据框中的列子集重新排序

pandas reorder subset of columns from a grouped data frame

我有按月分组的预测数据。 原始数据框 something 像这样:

>>clean_table_grouped[0:5]
       STYLE    COLOR    SIZE   FOR
MONTH                           01/17    10/16   11/16    12/16
    0 #######   ######   ####   0.0      15.0    15.0     15.0
    1 #######   ######   ####   0.0      15.0    15.0     15.0
    2 #######   ######   ####   0.0      15.0    15.0     15.0
    3 #######   ######   ####   0.0      15.0    15.0     15.0
    4 #######   ######   ####   0.0      15.0    15.0     15.0

>>clean_table_grouped.ix[0:,"FOR"][0:5] 
 MONTH  01/17  10/16  11/16  12/16
0        0.0   15.0   15.0   15.0
1        0.0   15.0   15.0   15.0
2        0.0   15.0   15.0   15.0
3        0.0   15.0   15.0   15.0
4        0.0   15.0   15.0   15.0

我只想按以下方式重新排列这 4 列:

(保持数据帧的其余部分不变)

MONTH    10/16  11/16  12/16  01/17
0        15.0   15.0   15.0   0.0
1        15.0   15.0   15.0   0.0
2        15.0   15.0   15.0   0.0
3        15.0   15.0   15.0   0.0
4        15.0   15.0   15.0   0.0

我尝试的解决方案是在下面的 post 之后对子集的列重新排序: How to change the order of DataFrame columns?

我先抓取列列表并对其进行排序

 >>for_cols = clean_table_grouped.ix[:,"FOR"].columns.tolist()
 >>for_cols.sort(key = lambda x: x[0:2])   #sort by month ascending
 >>for_cols.sort(key = lambda x: x[-2:])   #then sort by year ascending

查询数据框工作正常

>>clean_table_grouped.ix[0:,"FOR"][for_cols]
MONTH   10/16   11/16  12/16  01/17
0        15.0    15.0    15.0    0.0
1        15.0    15.0    15.0    0.0
2        15.0    15.0    15.0    0.0
3        15.0    15.0    15.0    0.0
4        15.0    15.0    15.0    0.0

但是,当我尝试在原始 table 中设置值时,我得到 table 的 "NaN":

>>clean_table_grouped.ix[0:,"FOR"] = clean_table_grouped.ix[0:,"FOR"][for_cols]
>>clean_table_grouped.ix[0:,"FOR"]
MONTH  01/17  10/16  11/16  12/16
0        NaN    NaN    NaN    NaN
1        NaN    NaN    NaN    NaN
2        NaN    NaN    NaN    NaN
3        NaN    NaN    NaN    NaN
4        NaN    NaN    NaN    NaN
5        NaN    NaN    NaN    NaN

我也尝试过压缩以避免链式语法 (.ix[][])。 这避免了 NaN,但是,它不会更改数据帧 -__-

>>for_cols = zip(["FOR", "FOR", "FOR", "FOR"], for_cols)
>>clean_table_grouped.ix[0:,"FOR"] = clean_table_grouped.ix[0:,for_cols]
>>clean_table_grouped.ix[0:,"FOR"]
 MONTH  01/17  10/16  11/16  12/16
 0        0.0   15.0   15.0   15.0
 1        0.0   15.0   15.0   15.0
 2        0.0   15.0   15.0   15.0
 3        0.0   15.0   15.0   15.0
 4        0.0   15.0   15.0   15.0

我知道我正在使用 ix 重新分配值。但是,我过去曾在未分组的数据帧上使用过这种技术,并且效果很好。

如果此问题已在另一个 post 中得到回答(以清晰的方式),请提供 link。我搜索了但找不到类似的东西。

编辑: 我找到了解决办法。通过按照您希望对列进行排序的顺序创建一个新的多索引数据框来手动重新索引。我 post 编辑了下面的解决方案。

对包含日期字符串的列名进行排序,然后将其用作 return 特定顺序的列的子集:

from datetime import datetime
df[sorted(df.columns, key=lambda x: datetime.strptime(x, '%m/%y'))]


玩具数据:

from datetime import datetime
np.random.seed(42)

cols = [['STYLE', 'COLOR', 'SIZE', 'FOR', 'FOR', 'FOR', 'FOR'],
        ['', '', '', '01/17', '10/16', '11/16', '12/16']]
tups = list(zip(*cols))
index = pd.MultiIndex.from_tuples(tups, names=[None, 'MONTH'])
clean_table_grouped = pd.DataFrame(np.random.randint(0, 100, (100, 7)), 
                                   index=np.arange(100), columns=index)
clean_table_grouped = clean_table_grouped.head()
clean_table_grouped

将多索引 DF 分成两部分,一个包含预测值,另一个包含剩余的 DF

for_df = clean_table_grouped[['FOR']]
clean_table_grouped = clean_table_grouped.drop(['FOR'], axis=1, level=0)

预测DF

for_df

剩余DF

clean_table_grouped

通过应用与预编辑 post 中相同的程序对预测 DF 中的列进行排序。

order = sorted(for_df['FOR'].columns.tolist(), key=lambda x: datetime.strptime(x, '%m/%y'))

通过对已排序的 list 列进行子集化,使 DF 的顺序相同。

for_df = for_df['FOR'][order]

将预测 DF 与其自身连接起来以创建类似多索引的列。

for_df = pd.concat([for_df, for_df], axis=1, keys=['FOR'])

最后,将它们加入共同索引。

clean_table_grouped.join(for_df)

我自己的解决方案是基于下面 post 的第二个答案: How can I reorder multi-indexed dataframe columns at a specific level

差不多...只需使用您想要的多索引创建一个新的数据框。 多索引数据帧不支持尝试使用 .ix、.loc、.iloc 插入值。如果您希望完全更改列子集的值(而不仅仅是交换),Nickil 的分离和重新连接表的解决方案绝对是可行的方法。但是,如果您只想交换列,则下面的工作非常好。我选择这个作为 Nickil 解决方案的答案,因为这个解决方案对我来说效果更好,因为除了按月分组 'FOR' 之外,我还有其他数据,它让我 更灵活地重新排序列 .

首先,按照您想要的顺序存储列表:

>>reindex_list = ['STYLE','COLOR','SIZE','FOR'] #desired order
>>month_list = clean_table_grouped.ix[0:,"FOR"].columns.tolist()
>>month_list.sort(key = lambda x: x[0:2]) #sort by month ascending
>>month_list.sort(key = lambda x: x[-2:]) #sort by year ascending

然后创建一个压缩列表,其中样式、颜色、尺寸用 '' 压缩,'FOR' 每个月压缩。像这样:

[('STYLE',''),('COLOR',''),..., ('FOR','10/16'), ('FOR','11/16'), ...]

这是一个自动执行此操作的算法:

>>zip_list = []
>>
for i in reindex_list:
if i in ['FOR']:
    for j in month_list:
        if j != '':
            zip_list.append(zip([i],[j])[0])
else:
    zip_list.append(zip([i],[''])[0])

然后从您刚刚压缩的元组列表中创建一个多索引:

>>multi_cols = pd.MultiIndex.from_tuples(zip_list, names=['','MONTH'])

最后,使用新的多索引从旧数据框创建一个新数据框:

>>clean_table_grouped_ordered = pd.DataFrame(clean_table_grouped, columns=multi_cols)
>>clean_table_grouped_ordered[0:5]
       STYLE COLOR SIZE FOR
 MONTH                  10/16   11/16   12/16  01/17
       ####  ####  ###  15.0    15.0    15.0    0.0
       ####  ####  ###  15.0    15.0    15.0    0.0
       ####  ####  ###  15.0    15.0    15.0    0.0
       ####  ####  ###  15.0    15.0    15.0    0.0
       ####  ####  ###  15.0    15.0    15.0    0.0
       ####  ####  ###  15.0    15.0    15.0    0.0