首页 > 解决方案 > 重复功能以提取相似信息

问题描述

这是我使用 pandas 打开和读取 json 文件的方法。我真的很欣赏熊猫的力量:)

import pandas as pd

df = pd.read_json("https://datameetgeobk.s3.amazonaws.com/cftemplates/EyeOfCustomer.json")

def mytype(mydict):
    try:
        if mydict["Type"]:
            return mydict["Type"]
    except:
        pass


df["myParametersType"] = df.Parameters.apply(lambda x: mytype(x))

问题是我还需要“描述”和“默认”值以及“类型”字符串。我已经编写了一个函数来提取上面提到的类型。我真的需要再写 2 个函数,如下所示?

def mydescription(mydict):
    try:
        if mydict["Description"]:
            return mydict["Description"]
    except:
        pass


def mydefault(mydict):
    try:
        if mydict["Default"]:
            return mydict["Default"]
    except:
        pass

df["myParametersDescription"] = df.Parameters.apply(lambda x: mydescription(x))
df["myParametersDefault"] = df.Parameters.apply(lambda x: mydefault(x))

如果字典包含超过 3 个键,我将如何处理它?

决赛桌应该是这样的......

df.iloc[:, -3:].dropna(how="all")

myParametersType    myParametersDescription myParametersDefault
pInstanceKeyName    AWS::EC2::KeyPair::KeyName  The name of the private key to use for SSH acc...   None
pTwitterTermList    String  List of terms for twitter to listen to  'your', 'search', 'terms', 'here'
pTwitterLanguages   String  List of languages to use for the twitter strea...   'en'
pTwitterAuthConsumerKey String  Consumer key for access twitter None
pTwitterAuthConsumerSecret  String  Consumer Secret for access twitter  None
pTwitterAuthToken   String  Access Token Secret for calling twitter None
pTwitterAuthTokenSecret String  Access Token Secret for calling twitter None
pApplicationName    String  Name of the application deploying for the EyeO...   EyeOfCustomer
pVpcCIDR    String  Please enter the IP range (CIDR notation) for ...   10.193.0.0/16
pPublicSubnet1CIDR  String  Please enter the IP range (CIDR notation) for ...   10.193.10.0/24

标签: pythonjsonpandas

解决方案


您可以将新参数传递给函数:

def func(mydict, val):
    try:
        if mydict[val]:
            return mydict[val]
    except:
        pass

df["myParametersType"] = df.Parameters.apply(lambda x: func(x, 'Type'))
df["myParametersDescription"] = df.Parameters.apply(lambda x: func(x, 'Description'))
df["myParametersDefault"] = df.Parameters.apply(lambda x: func(x, 'Default'))
df = df.iloc[:, -3:].dropna(how="all")

推荐阅读