【发布时间】: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