如何根据条件对多索引数据帧进行groupby

问题描述 投票:0回答:1

我有一个多索引数据框,我想根据某些条件组合行,并且我想组合每个索引的行。

import pandas as pd

#  data
data = {
    'date': ['01/01/17', '02/01/17', '03/01/17', '01/01/17', '02/01/17', '03/01/17'],
    'language': ['python', 'python', 'python', 'r', 'r', 'r'],
    'ex_complete': [6, 5, 10, 8, 8, 8]
}

# Convert to DataFrame
df = pd.DataFrame(data)

# Convert DataFrame to JSON
json_data = df.to_json(orient='records')

# Convert JSON data back to DataFrame
df_from_json = pd.read_json(json_data, orient='records')

# Set date and language as multi-index
df_from_json.set_index(['date', 'language'], inplace=True)

df_from_json.sort_index(inplace= True)

df_from_json

第一个问题:

我想合并日期“01/01/17”、“02/01/17”并重命名为“1_2”,这应该给我 4 行: “1_2”有 2 行 -(Python 和 R),“03/01/17”有 2 行(Python 和 R)

第二个问题:

我想合并 Python 和 R 行并重命名为 Python_R,这应该为 3 个日期提供 3 行。

任何指导或指示将不胜感激。

python pandas dataframe data-wrangling
1个回答
0
投票

IIUC用途:

out = df.replace({'date':{'01/01/17':'1_2','02/01/17':'1_2'},
                  'language':{'python':'Python_R', 'r':'Python_R'}})
print (out)
       date  language  ex_complete
0       1_2  Python_R            6
1       1_2  Python_R            5
2  03/01/17  Python_R           10
3       1_2  Python_R            8
4       1_2  Python_R            8
5  03/01/17  Python_R            8
© www.soinside.com 2019 - 2024. All rights reserved.