【问题标题】:Filtering dict to dataframe将dict过滤到数据框
【发布时间】:2022-08-18 15:42:15
【问题描述】:

我在将 dict 过滤到数据框时遇到问题

我有数据框:

location recipient material type colour
store bottle ZN_PLASTIC bin red
store bottle ZN_PLASTIC_GR bin red
store bottle ZN_PLASTIC_BL bin red
store bottle ZN_PLASTIC_WH bin red
store bottle ZN_PLASTIC_TP bin red
store bottle ZN_GLASS bin green
store bottle ZN_GLASS_GR bin green
store bottle ZN_GLASS_BL bin green
store bottle ZN_GLASS_WR bin green
store bottle ZN_GLASS_TP bin green

按材料类别创建数据框:

plastic = data.loc[data[\'material\'].str.contains(\'PLASTIC\') == True]              
glass = data.loc[data[\'material\'].str.contains(\'GLASS\') == True]

为塑料类型创建一个字典:

plastic_dict = {}
for klass in plastic[\'material\'].unique():
    plastic_dict[klass] = plastic[plastic[\'material\'].str.contains(klass)]

展示:

plastic_dict.keys()

输出:

dict_keys([\'ZN_PLASTIC\', \'ZN_PLASTIC_GR\', \'ZN_PLASTIC_BL\', \'ZN_PLASTIC_WH\', \'ZN_PLASTIC_TP\'])

为玻璃类型创建一个字典:

glass_dict = {}
for klass in glass[\'material\'].unique():
    glass_dict[klass] = glass[glass[\'material\'].str.contains(klass)]

展示:

glass_dict.keys()

输出:

dict_keys([\'ZN_GLASS\', \'ZN_GLASS_GR\', \'ZN_GLASS_BL\', \'ZN_GLASS_WH\', \'ZN_GLASS_TP\'])

现在,我正在尝试使用 dict 过滤一些数据并创建一个数据框:

ac_plastic_ = {}
for i in plastic_dict.keys():
    locals()[f\"ac_plastic_{i}\"] = plastic_dict[i]
    locals()[f\"ac_plastic_{i}\"].to_csv (r\'ac_plastic_\' + str(i) + \'.txt\', index = None, header=False, sep=\'\\t\', encoding=\'utf-8\')

但是过滤器失败了,我有以下内容:

display(ac_plastic_ZN_PLASTIC)

输出:

location recipient material type colour
store bottle ZN_PLASTIC bin red
store bottle ZN_PLASTIC_GR bin red
store bottle ZN_PLASTIC_BL bin red
store bottle ZN_PLASTIC_WH bin red
store bottle ZN_PLASTIC_TP bin red

对于更具体的句子,过滤器起作用:

display(ac_plastic_ZN_PLASTIC_GR)

输出:

location recipient material type colour
store bottle ZN_PLASTIC_GR bin red

我试图修复失败。 那么,如何解决这个问题呢?

谢谢

  • 你想要的输出是什么?
  • 请发布最少的代码、最少且充分的解释,以及最重要的是最少的可重现示例

标签: python pandas dictionary


【解决方案1】:

问题是因为您在创建字典时使用了pandas.Series.str.contains

glass_dict = {}
for klass in glass['material'].unique():
    glass_dict[klass] = glass[glass['material'].str.contains(klass)]

因此,您在string 中获取包含ZN_PLASTIC 的所有行,您需要做的是匹配确切的klass

plastic_dict = {}
for klass in plastic['material'].unique():
    plastic_dict[klass] = plastic.loc[plastic['material'] == klass]

笔记:在创建部分dataframes 时始终使用lociloc 选择行,否则稍后在尝试应用其他功能时可能会遇到与切片或副本相关的错误。

【讨论】:

    猜你喜欢
    • 2018-12-02
    • 2019-03-26
    • 2021-02-05
    • 2019-09-27
    • 2018-01-03
    • 2021-11-24
    • 2021-04-22
    • 2011-11-23
    相关资源
    最近更新 更多