如何根据字典键将列添加到pandas数据框?

时间:2016-04-13 08:27:39

标签: python dictionary pandas

我在pandas中有一个包含12列的数据帧。一列是useragent string wchich我想提取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 platform 列添加到数据框中。 问题首先是在未执行try之后的第一个赋值。 我将赋值放在try块中,因为从解析器返回的dictinories总是没有相同的键。例如,如果返回字典中不存在键os,则该索引的新列os应为Null。 如何以有效的方式完成整个过程?

1 个答案:

答案 0 :(得分:1)

它无法正常工作的原因是您无法在DataFrame上设置切片副本(此警告已被try / except隐藏)。

对于数据框的所有行,您可以安全地在一行中执行以下操作:

df['platform'] = df.apply(
    lambda k: httpagentparser.detect(k['useragent']).get('platform', {}).get('name'),
    axis=1
)
相关问题