我有一个包含12列的熊猫数据框。一列是useragent字符串,我想提取os,browser和....等信息,并根据这些值向数据框添加新列。 列平台在当前数据框中不存在,我想将其添加到位。如何根据字典键向熊猫数据框添加列?
a b c useragent
1 3 5 "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"
a b c useragent os platform
1 3 5 same as before windows Null
for i in range(len(df["useragent"])):
try :
df['platform'].iloc[i] = httpagentparser.detect(df["useragent"].iloc[i])['platform']['name']
except :
continue
我要添加列OS和平台基于从解析器值数据框。 该问题首先是在尝试未执行后的第一次分配。 我把这个任务放在try块中,因为从解析器返回的字典没有总是相同的密钥。例如,如果返回字典中不存在关键字os,则该索引的新列os应该为空。 如何以有效的方式完成整个过程?
你可以添加[最小的,完整的和可验证的示例](http://stackoverflow.com/help/mcve )? – jezrael
我加了一个例子 – Kaggle