简体   繁体   English

使用多索引熊猫数据框

[英]Working with multi-index pandas dataframe

I am working with a multi-index data frame but I am having a few problems while trying to filter/update its values. 我正在使用多索引数据框,但是在尝试过滤/更新其值时遇到一些问题。

What I need: 我需要的:

  1. Change 'Name 1', 'Name 2' and the others to upper case 将“名称1”,“名称2”和其他名称更改为大写
  2. Get all the names with value 1 in {Group 1+ A} for example 例如,获取{Group 1+ A}中所有值为1的名称
  3. Get the list of the names in the previous step after selection (NAME 1, NAME 2, etc) 选择后,获取上一步中的名称列表(NAME 1,NAME 2等)

If I could also convert this MultiIndex data frame into a "normal" data frame it would be fine too. 如果我也可以将此MultiIndex数据帧转换为“正常”数据帧,那也很好。

A sample code: 示例代码:

import pandas as pd

sample_file = '.../Sample.xlsx'

excel_file = pd.ExcelFile(sample_file)
df = excel_file.parse(header=[0, 1], index_col=[0], sheet_name=0)

# Upper case columns
c_cols = licensing_df.columns.get_level_values(0).str.upper()
s_cols = licensing_df.columns.get_level_values(1).str.upper()
licensing_df.columns = pd.MultiIndex.from_arrays([c_cols, s_cols])

# TODO: step 1

# Step 2
valid = df[df[('GROUP 1', 'A')] == 1]

# TODO: Step 3

This is the sample file I am using: Sample file 这是我正在使用的示例文件示例文件

This is a sample picture of a data frame: 这是数据帧的示例图片:

在此处输入图片说明

Thank you! 谢谢!

I can only assume what you're trying to achieve since you did not provide an input sample. 由于您未提供输入示例,因此我只能假设您要实现的目标。

If you're trying to select and modify a specific row with a MultIndex you can use the .loc operator and the corresponding tuple that you specified in the MultiIndex, eg 如果尝试使用MultIndex选择和修改特定行,则可以使用.loc运算符以及在MultiIndex中指定的相应元组,例如

df.loc['Name1', ('GROUP 1', 'A')]

Let's mock some data... 让我们模拟一些数据...

index = pd.MultiIndex.from_product([[2013, 2014], [1, 2]],
                                    names=['year', 'visit'])
columns = pd.MultiIndex.from_product([['Bob', 'Guido', 'Sue'], ['HR', 'Temp']],
                                      names=['subject', 'type'])
data=np.array(list(string.ascii_lowercase))[:24].reshape((4, 6))

df = pd.DataFrame(
    columns=columns,
    index=index,
    data=data
)

Here's our MultiIndex DataFrame: 这是我们的MultiIndex DataFrame:

subject    Bob      Guido      Sue     
type        HR Temp    HR Temp  HR Temp
year visit                             
2013 1       a    b     c    d   e    f
     2       g    h     i    j   k    l
2014 1       m    n     o    p   q    r
     2       s    t     u    v   w    x

Let's select the first row and change the letters to uppercase... 让我们选择第一行并将字母更改为大写...

df.loc[(2013, 1)].str.upper()

...and likewise for the first column... ...对于第一栏同样...

df.loc[('Bob', 'HR')].str.upper()

...and finally we pick a specific cell ...最后我们选择一个特定的单元格

df.loc[(2014, 1), ('Guido', 'HR')].upper()

which returns 哪个返回

'O'

I hope that gives you an idea of how to use the .loc operator.... 我希望这能使您了解如何使用.loc运算符。

User your excel file: 使用您的Excel文件:

df = pd.read_excel('Downloads/Sample.xlsx', header=[0,1], index_col=0)
df

Output: 输出:

Lists  Group 1                                         ... Group 2                                         
Name        AR   AZ   CA   CO  CT   FL  GA   IL IN KY  ...      SC  SD   TN   TX   UT   VA WA   WI  WV   WY
Name 1     NaN  1.0  1.0  1.0 NaN  1.0 NaN  NaN  1  1  ...       1 NaN  1.0  1.0  1.0  1.0  1  1.0 NaN  1.0
Name 2     NaN  NaN  NaN  NaN NaN  1.0 NaN  1.0  1  1  ...       1 NaN  1.0  NaN  NaN  1.0  1  NaN NaN  NaN
Name 3     NaN  NaN  NaN  NaN NaN  NaN NaN  1.0  1  1  ...       1 NaN  NaN  NaN  NaN  NaN  1  NaN NaN  NaN

[3 rows x 72 columns]

To Do #1 要做#1

df.index = df.index.str.upper()
df

Output: 输出:

Lists  Group 1                                         ... Group 2                                         
Name        AR   AZ   CA   CO  CT   FL  GA   IL IN KY  ...      SC  SD   TN   TX   UT   VA WA   WI  WV   WY
NAME 1     NaN  1.0  1.0  1.0 NaN  1.0 NaN  NaN  1  1  ...       1 NaN  1.0  1.0  1.0  1.0  1  1.0 NaN  1.0
NAME 2     NaN  NaN  NaN  NaN NaN  1.0 NaN  1.0  1  1  ...       1 NaN  1.0  NaN  NaN  1.0  1  NaN NaN  NaN
NAME 3     NaN  NaN  NaN  NaN NaN  NaN NaN  1.0  1  1  ...       1 NaN  NaN  NaN  NaN  NaN  1  NaN NaN  NaN

[3 rows x 72 columns]

To Do #2 要做#2

df[df.loc[:, ('Group 1', 'AZ')] == 1].index.to_list()

Output: 输出:

['NAME 1']

To Do #3 要做#3

df[df.loc[:, ('Group 1', 'IL')] == 1].index.to_list()

Output: 输出:

['NAME 2', 'NAME 3']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM