旋转多索引D

2024-05-19 11:31:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个多索引pandas数据帧,如下所示:

Input

我希望不同的四分之一是行而不是层次列,即长格式而不是宽格式。如下所示(输出不必是multindex):

output

我怎么能在熊猫身上做到这一点?在

编辑:

请求的输入文件示例:

rbi_credits_data.xlsx

样本数据(熊猫):

cols = pd.MultiIndex(levels=[['Center_Details', '2017-18:Q2', '2017-18:Q1'],
                       ['State', 'District', 'Center', 'Offices', 'Deposit', 'Credit']],
               labels=[[0, 0, 0, 1, 1, 1, 2, 2, 2],
                       [0, 1, 2, 3, 4, 5, 3, 4, 5]])
data = [['JAMMU & KASHMIR', 'KUPWARA', 'Drug Mulla (CT)', '3', '500', '600', '4', '500', '600'], 
    ['JAMMU & KASHMIR', 'LEH LADAKH', 'Chuglamsar (CT)', '3', '500', '600', '4', '500', '600'], 
    ['PUNJAB', 'PATHANKOT', 'Mamun (CT)', '3', '500', '600', '4', '500', '600'], 
    ['PUNJAB', 'GURDASPUR', 'TIBRI', '3', '500', '600', '4', '500', '600']]
df = pd.DataFrame(data=data, columns=cols)

Tags: 文件数据编辑示例pandasdata格式pd
2条回答

稍微修改一下@A5C1D2H2I1M1N2O1R2T1的答案,我发现我仍然可以保留多索引结构:

idx = df[['Center_Details']].columns.values.tolist()
long = pd.melt(df, id_vars = idx)

# Renaming variable created by melt to a multiindex friendly name
long.rename(columns={'variable_0': ('Values', 'Qtr')}, inplace=True)

# Reshape to wide format, keeping Values, QTR as a hierarchical column
out = pd.pivot_table(long, index = idx + [('Values', 'Qtr')], columns = 'variable_1', 
                 values = 'value', aggfunc = 'first')

# Creating tuples for new column names
out.columns = [('Values', col) for col in out.columns]
out = out.reset_index()
# Converting columns to multiindex
out.columns = pd.MultiIndex.from_tuples(out.columns.values)
print(out)

+ -+        -+      +        -+      +    +    -+    -+
|   | Center_Details  |            |                 | Values     |        |         |         |
+ -+        -+      +        -+      +    +    -+    -+
|   | State           | District   | Center          | QTR        | Credit | Deposit | Offices |
+ -+        -+      +        -+      +    +    -+    -+
| 0 | JAMMU & KASHMIR | KUPWARA    | Drug Mulla (CT) | 2017-18:Q1 | 600    | 500     | 4       |
+ -+        -+      +        -+      +    +    -+    -+
| 1 | JAMMU & KASHMIR | KUPWARA    | Drug Mulla (CT) | 2017-18:Q2 | 600    | 500     | 3       |
+ -+        -+      +        -+      +    +    -+    -+
| 2 | JAMMU & KASHMIR | LEH LADAKH | Chuglamsar (CT) | 2017-18:Q1 | 600    | 500     | 4       |
+ -+        -+      +        -+      +    +    -+    -+
| 3 | JAMMU & KASHMIR | LEH LADAKH | Chuglamsar (CT) | 2017-18:Q2 | 600    | 500     | 3       |
+ -+        -+      +        -+      +    +    -+    -+
| 4 | PUNJAB          | GURDASPUR  | TIBRI           | 2017-18:Q1 | 600    | 500     | 4       |
+ -+        -+      +        -+      +    +    -+    -+
| 5 | PUNJAB          | GURDASPUR  | TIBRI           | 2017-18:Q2 | 600    | 500     | 3       |
+ -+        -+      +        -+      +    +    -+    -+
| 6 | PUNJAB          | PATHANKOT  | Mamun (CT)      | 2017-18:Q1 | 600    | 500     | 4       |
+ -+        -+      +        -+      +    +    -+    -+
| 7 | PUNJAB          | PATHANKOT  | Mamun (CT)      | 2017-18:Q2 | 600    | 500     | 3       |
+ -+        -+      +        -+      +    +    -+    -+

PS:很抱歉表格格式太难看了,我还是不知道如何在上面创建表格。在

一种方法可以是将MultiIndex展平,然后使用melt和{},如下所示:

# Flatten the MultiIndex columns
df.columns = [' '.join(col).strip() for col in df.columns.values]

# Save some typing
idx = ['Center_Details State', 'Center_Details District', 'Center_Details Center']

# Create a long dataframe
long = pd.melt(df, id_vars = idx)

# Split the "variable" column at the space created when flattening the MultiIndex
long['QTR'], long['item'] = zip(*long['variable'].map(lambda x: x.split(' ')))

# Reshape to wide format, keeping "QTR" as a column
out = pd.pivot_table(long, index = idx + ["QTR"], columns = 'item', 
                     values = 'value', aggfunc = 'first').reset_index()
print(out)
item Center_Details State Center_Details District Center_Details Center  \
0         JAMMU & KASHMIR                 KUPWARA       Drug Mulla (CT)   
1         JAMMU & KASHMIR                 KUPWARA       Drug Mulla (CT)   
2         JAMMU & KASHMIR              LEH LADAKH       Chuglamsar (CT)   
3         JAMMU & KASHMIR              LEH LADAKH       Chuglamsar (CT)   
4                  PUNJAB               GURDASPUR                 TIBRI   
5                  PUNJAB               GURDASPUR                 TIBRI   
6                  PUNJAB               PATHANKOT            Mamun (CT)   
7                  PUNJAB               PATHANKOT            Mamun (CT)   

item         QTR Credit Deposit Offices  
0     2017-18:Q1    600     500       4  
1     2017-18:Q2    600     500       3  
2     2017-18:Q1    600     500       4  
3     2017-18:Q2    600     500       3  
4     2017-18:Q1    600     500       4  
5     2017-18:Q2    600     500       3  
6     2017-18:Q1    600     500       4  
7     2017-18:Q2    600     500       3  

另一种选择可能是:

^{pr2}$

第三个选项是使用wide_to_long,但是wide_to_long要求宽格式的列在开头有存根。该方法与第一种方法类似,但步骤较少。在

它看起来像:

# Flatten the column names, but reverse the order of the tuples
#   before flattening, and add a character to split on
df.columns = ['~'.join(col[::-1]).strip() for col in df.columns.values]

# Reshape the data, Stata-style
pd.wide_to_long(df, ['Offices', 'Deposit', 'Credit'], 
   i=['State~Center_Details', 'District~Center_Details', 'Center~Center_Details'],
   j='Quarter', sep='~').reset_index()

你仍然需要对“中心细节”列做一些清理。在

相关问题 更多 >

    热门问题