python - 重复功能以提取相似信息
问题描述
这是我使用 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
解决方案
您可以将新参数传递给函数:
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")
推荐阅读
- generator - Redux Saga 如何解析数据
- mocking - C++ 模拟类 - 如何解决这个多重继承问题?
- sql - 将日期字段值插入 varcharfield 以及附加的硬编码文本
- python - 使用方差膨胀因子查找属性之间的多重共线性
- c - 在用户输入每个数组位置的值时对数组进行排序
- r - 如何从数据集中删除多个年月
- python - 使用 Mathplotlib.pyplot 不会显示 Scipy 插值网格数据
- python-2.7 - AttributeError:“模块”对象没有属性“Ed25519Key”
- asp.net - 关于 IHttpModule 实现的私有字段的问题
- if-statement - 无法让滑块在间隔之间打印不同的文本