将字典添加到熊猫数据框,并忽略其他值

时间:2019-07-25 06:11:20

标签: python pandas dataframe dictionary

我正在读取许多日志文件,我通过解析每个日志从中生成字典,我想将此字典添加到数据框中,稍后再使用此数据框进行分析。但是,根据用户输入的不同,我每次在数据框中需要的信息可能会有所不同。所以我不希望字典中的所有信息都添加到数据框中。我希望在数据框中定义的列仅添加到数据框中。

到目前为止,我将所有字典一个一个地添加到列表中,然后将此字典加载到数据帧中。

for log in log_lines:
    # here logic to parse the log and generate the dictionary
    my_dict_list.append(d)
pd.Dataframe(my_dict_list)

通过这种方式,它将所有键及其值添加到数据框中, 但是我想要的是,我将定义一些列,假设用户要求['a','b','c']列进行分析,我希望数据框仅将这些键及其值加载到数据框,其余应忽略。

my_dict_list =[ {'a':'abc','b':'123','c':'hello', 'date':'20-5-2019'},
                {'a':'dfc','b':'453','c':'user', 'date':'23-5-2019'},
                {'a':'bla','b':'2313','c':'anything', 'date':'25-5-2019'} ]

注意:我不希望在提取日志时忽略键,因为我将提取很多日志,因此很费时间。

有没有一种方法可以更快地使用熊猫呢?

2 个答案:

答案 0 :(得分:0)

我只是为您的查询提供一些原始逻辑,我在某些方面可能是错误的,但是如果您发现对您有帮助,那将是非常不错的,您也可以将我的邮件也寄给我,以便将来查询,我将很乐意为您提供帮助。

android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

答案 1 :(得分:0)

tmp_Dict行中,您只能过滤请求的列并仅保存请求的列。

def log_dataframe(log_lines, requested_columns):
    for log in log_lines:
        # here logic to parse the log and generate the dictionary

        tmp_Dict = {requested_key : d[requested_key] for requested_key in request_columns}
        my_dict_list.append(tmp_Dict)
    return pd.Dataframe(my_dict_list)