本文介绍了如何在 pandas 堆叠之前动态重命名列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用groupby和sum创建了以下数据框:-

I have the below dataframe created using groupby and sum :-

year_month  Country           
2008-01     Afghanistan             2
            Albania                 3
            Argentina               4
2008-02     Afghanistan             3
            Albania                 4
            Argentina               5

我需要拆开包装,并希望将名称重命名为der_value_Afghanistan,der_value_Albania等作为列名,而不是阿富汗等.既然可能是100个或更多,那么有什么办法可以全部重命名而不是手动重命名?

I need to unstack and want name to be renamed as der_value_Afghanistan, der_value_Albania etc as column names rather than Afghanistan etc. Since it could be 100 or more, is there any way to rename it all together rather than manually?

year_month der_value_Afghanistan der_value_Albania der_value_Argentina

推荐答案

我认为需要 Series.unstack DataFrame.add_prefix :

I think need Series.unstack with DataFrame.add_prefix:

df = s.unstack().add_prefix('der_value_')
print (df)
Country     der_value_Afghanistan  der_value_Albania  der_value_Argentina
year_month                                                               
2008-01                         2                  3                    4
2008-02                         3                  4                    5

对于index到列中添加 DataFrame.reset_index :

For index to column add DataFrame.rename_axis with DataFrame.reset_index:

df = s.unstack().add_prefix('der_value_').rename_axis(None, axis=1).reset_index()
print (df)
  year_month  der_value_Afghanistan  der_value_Albania  der_value_Argentina
0    2008-01                      2                  3                    4
1    2008-02                      3                  4                    5


也可以通过 MultiIndex.from_arrays :


Modify MultiInex before unstack is also possible by MultiIndex.from_arrays:

a = s.index.get_level_values(0)
b = 'der_value_' + s.index.get_level_values(1)
s.index = pd.MultiIndex.from_arrays([a, b], names=s.index.names)
print (s)
year_month  Country              
2008-01     der_value_Afghanistan    2
            der_value_Albania        3
            der_value_Argentina      4
2008-02     der_value_Afghanistan    3
            der_value_Albania        4
            der_value_Argentina      5
Name: a, dtype: int64

df = s.unstack()
print (df)
Country     der_value_Afghanistan  der_value_Albania  der_value_Argentina
year_month                                                               
2008-01                         2                  3                    4
2008-02                         3                  4                    5

这篇关于如何在 pandas 堆叠之前动态重命名列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 14:37