python - 对熊猫数据字段的速记引用?
问题描述
我正在使用 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”。
解决方案
假设您有一个如下所示的数据框
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
推荐阅读
- angular - 动态渲染角度模板时如何捕获错误
- wikidata - 如何检索实体的完整维基数据信息
- node.js - ExpressJS 日期和时间冻结
- python - 请建议使用 Python 对电子邮件标题字符串值进行模糊匹配的改进
- php - PHP使用来自mysql查询的结果字段值作为邮件接收者
- regex - htaccess - 重写以特定字符串结尾的 URL 并捕获唯一部分
- angular - 对基于自定义 ReplaySubject 的 observable 的同步阻塞订阅调用
- azure-cognitive-search - 是否可以获得类似和/相同文件的列表?
- javascript - 从 Firestore 保存数据
- ruby-on-rails - 如何删除rails中的部分url?