熊猫专栏清理

时间:2017-12-27 05:26:24

标签: pandas

我在pandas中有一个带有复杂列的数据集。列product_info之一具有各种类型的内容:

#Input type1
df['productInfo'][0]
#Output type1
'Salt & pepper shakers,Material: stoneware,Dimensions: 
H6.5cm,Dachshund designs,1x black and tan, 1x brown,Hand 
painted,Dishwasher safe'
#Output type2
'Pineapple string lights,Dimensions: 400x6x10cm,10 pineapple shaped LED lights,In a gold hue,3x AA batteries required (not included)'
#Output type 3
''

基本上我的productInfo列包含上述3种内容。 我想要的是获取用于groupby分析的Material:从数据框的productInfo列中提取,当然只有当这些值存在时,如果它们不存在,只需将这些值设置为null / None或其他

我尝试过布尔蒙版,但似乎无法使它们发挥作用,任何有任何建议的人都会受到高度赞赏。

提前致谢

编辑: 这是我原来的df: original df

从ProductInfo中提取材料后我的df: df after extracting Material from ProductInfo

从ProductInfo中提取材质和尺寸后的我的df: enter image description here

希望你们能够了解我想要实现的目标。我的大多数任务是从每列内部的复杂文本blob中提取文本。  如果我使用正则表达式找到文本块中的相关列,那么我更新列,否则使它们为空。事实证明这是一个很大的挑战,如果你们中的任何人能够帮助我从productInfo文本丛中提取材料和尺寸等有用的信息到他们自己的专栏,那对你们来说非常有帮助。

感谢任何试图帮助我的人,并在不提供相关信息的情况下对我的模糊问题表示抱歉。

快乐熊猫(如果这是一个字!!) :)

1 个答案:

答案 0 :(得分:0)

我导入了 pandasre

import pandas as pd
import re

我创建了一个辅助函数,它执行一个简单的正则表达式来获取材料和尺寸。我从原始字符串中删除了材料和尺寸字符串,返回带有更新的描述、材料和尺寸的系列。

def get_material_and_dimensions(row):
    description = row['productInfo']

    material = re.search(r'Material: (.*?),', description)
    if material:
        material = material.group(1)
        description = description.replace(f'Material: {material},', '')

    dimensions = re.search(r'Dimensions: (.*?),', description)
    if dimensions:
        dimensions = dimensions.group(1)
        description = description.replace(f'Dimensions: {dimensions},', '')

    return pd.Series([description, material, dimensions], index=['description', 'material', 'dimensions'])

将函数应用到DataFrame

myseries = df.apply(get_material_and_dimensions, axis=1)

然后将系列添加到原始 DataFrame,将 df['productInfo'] 替换为干净的 df['description']

df = df.join(myseries)
df['productInfo'] = df['description']
df.drop('description', inplace=True, axis=1)