首页 > 解决方案 > 对熊猫数据字段的速记引用?

问题描述

我正在使用 pandas 并尝试创建一些字典来存储与特定唯一行值有关的数据字段。

示例数据:

Date, Indicator, Income
01 Jan 2000, 1.01.02 Sales, $400
02 Jan 2000, 1.01.02 Sales, $600
07 July 2000, 3.01.03 Exports, $500

示例代码:

Indicators = df['Indicator'].unique().tolist()
# to create a datafield for each unique indicator under the Indicators heading
I_dict = {I: df.loc[df['Indicator'] == I] for I in Indicators}

我的问题是指标本身真的很长 - 他们在开始时有一个代码来识别它们,但我不知道如何将它们分开并仍然遵循这个过程。

为了解决这个问题,我正在使用以下内容:(指标在哪里'3.05.10 Overseas Exports'

print(I_dict['3.05.10 Overseas Exports'])

我宁愿用“3.05.10”来标记它。 这可能吗?另一个问题是并非所有的代码都是那个长度——有些是“5.02”。

标签: pythonregexpandas

解决方案


假设您有一个如下所示的数据框

df
           Date        Indicator Income
0   01 Jan 2000    1.01.02 Sales   $400
1   02 Jan 2000    1.01.02 Sales   $600
2  07 July 2000  3.01.03 Exports   $500
3   01 Jan 2000     1.01 Sales A   $400
4   02 Jan 2000     1.01 Sales A   $600
5  07 July 2000   3.01 Exports A   $500

你能做的是

import re

# this regex captures all the digits and dots. the last dot-digit combination
# is optional
r = re.compile(r"(\d+\.\d+(?:\.\d+)?)")

# create a short indicator
df['ShortInd'] = df.Indicator.map(lambda x: r.search(x).group(0))
df
           Date        Indicator Income ShortInd
0   01 Jan 2000    1.01.02 Sales   $400  1.01.02
1   02 Jan 2000    1.01.02 Sales   $600  1.01.02
2  07 July 2000  3.01.03 Exports   $500  3.01.03
3   01 Jan 2000     1.01 Sales A   $400     1.01
4   02 Jan 2000     1.01 Sales A   $600     1.01
5  07 July 2000   3.01 Exports A   $500     3.01

# create your dictionary
i_dict = {g: sub_df for g, sub_df in df.groupby('ShortInd')}

i_dict.keys()
dict_keys(['1.01', '1.01.02', '3.01', '3.01.03'])

i_dict['1.01']
          Date     Indicator Income ShortInd
3  01 Jan 2000  1.01 Sales A   $400     1.01
4  02 Jan 2000  1.01 Sales A   $600     1.01

推荐阅读