python - Pandas 映射到多个字典项以对数据进行分类

标签 python pandas dictionary

我有一个包含 'Description' 列的大型数据框。

我已经编译了一个相当大的列表字典,其中键基本上是类别,项目是描述列中包含的可能(子)字符串的列表。 我想使用字典根据此描述对数据框中的每个条目进行分类...不幸的是,我无法弄清楚如何应用列表字典来映射到数据帧(感觉就像是某种混合物) mapisinstr.contains 但我没有任何喜悦)。我在下面包含了生成模型数据集的代码:

df = pd.DataFrame(np.random.randn(10, 1), columns=list('A'))

df['Description'] = ['White Ford Escort', 'Irish Draft Horse', 'Springer \
spaniel (dog)', 'Green Vauxhall Corsa', 'White Van', 'Labrador dog',\
'Black horse' ,'Blue Van','Red Vauxhall Corsa','Bear']

理想情况下,该模型数据集将以某种方式映射到以下字典:

dict = {'Car':['Ford Escort','Vauxhall Corsa','Van'],
        'Animal':['Dog','Horse']}

在数据框中生成一个新列,结果如下:

|   | A                    | Description            | Type   |
|---|----------------------|------------------------|--------|
| 0 | -1.4120290137842615  | White Ford Escort      | Car    |
| 1 | -0.3141036399049358  | Irish Draft Horse      | Animal |
| 2 | 0.49374344901643896  | Springer spaniel (dog) | Animal |
| 3 | 0.013654965767323723 | Green Vauxhall Corsa   | Car    |
| 4 | -0.18271952280002862 | White Van              | Car    |
| 5 | 0.9519081000007026   | Labrador dog           | Animal |
| 6 | 0.403258571154998    | Black horse            | Animal |
| 7 | -0.8647792960494813  | Blue Van               | Car    |
| 8 | -0.12429427259820519 | Red Vauxhall Corsa     | Car    |
| 9 | 0.7695980616520571   | Bear                   | -      |

这些数字显然与这里无关,但数据框中还有其他列,我希望反射(reflect)出来。 我很高兴使用正则表达式,或者可能将我的字典更改为数据框并进行连接(我考虑过多个路由)。

这感觉与最近的question类似。 ,但它不一样,而且答案当然对我没有帮助。

抱歉,如果我在某个地方犯了蠢,这真的很简单 - 感觉确实应该如此,但我错过了一些东西。

谢谢

最佳答案

您可以使用fuzzywuzzy库来解决这个问题。确保通过 pip install fuzzywuzzy

安装它
from fuzzywuzzy import process

df = pd.DataFrame(np.random.randn(10, 1), columns=list('A'))

df['Description'] = ['White Ford Escort', 'Irish Draft Horse', 'Springer \
spaniel (dog)', 'Green Vauxhall Corsa', 'White Van', 'Labrador dog',\
'Black horse' ,'Blue Van','Red Vauxhall Corsa','Bear']

d = {'Car':['Ford Escort','Vauxhall Corsa','Van'],
    'Animal':['Dog','Horse']}

# Construct a dataframe from the dictionary
df1 = pd.DataFrame([*d.values()], index=d.keys()).T.melt().dropna()

# Get relevant matches using the library.
m = df.Description.apply(lambda x: process.extract(x, df1.value)[0])

# concat the matches with original df
df2 = pd.concat([df, m[m.apply(lambda x: x[1]>80)].apply(lambda x: x[0])], axis=1)

df2.columns = [*df.columns, 'matches']

# After merge it with df1
df2 = df2.merge(df1, left_on='matches', right_on='value', how='left')

# Drop columns that are not required and rename.
df2 = df2.drop(['matches','value'],1).rename(columns={'variable':'Type'})

print (df2)

          A             Description    Type
0 -0.423555       White Ford Escort     Car
1  0.294092       Irish Draft Horse  Animal
2  1.949626  Springer spaniel (dog)  Animal
3 -1.315937    Green Vauxhall Corsa     Car
4 -0.250184               White Van     Car
5  0.186645            Labrador dog  Animal
6 -0.052433             Black horse  Animal
7 -0.003261                Blue Van     Car
8  0.418292      Red Vauxhall Corsa     Car
9  0.241607                    Bear     NaN

关于python - Pandas 映射到多个字典项以对数据进行分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53508322/

相关文章:

javascript - 如何将url中的变量传递给pythonflask

python - Pandas .resample() 方法 - 自定义标签?

python - Pandas:如何在函数内将 sum() 或 mean() 分配给 df.groupby?

Swift二维字典错误

Python Merge 2 or more Dicts using a value to handle duplicate keys

python - 如何在 django 中包装管理 View ?

python - 如何使用numpy镶嵌数组?

python - 是否有一种有效/最佳的方法来为 Pandas 数据框列中的值分配分数?

python - 尝试根据每行另一列行的值拆分数据框列

C++ - 迭代 vector 的替代方法