相关疑难解决方法(0)

将Pandas列内的字典/列表拆分为单独的列

我将数据保存在postgreSQL数据库中.我使用Python2.7查询这些数据并将其转换为Pandas DataFrame.但是,此数据框的最后一列中包含值的字典(或列表?).DataFrame看起来像这样:

[1] df
Station ID     Pollutants
8809           {"a": "46", "b": "3", "c": "12"}
8810           {"a": "36", "b": "5", "c": "8"}
8811           {"b": "2", "c": "7"}
8812           {"c": "11"}
8813           {"a": "82", "c": "15"}
Run Code Online (Sandbox Code Playgroud)

我需要将此列拆分为单独的列,以便DataFrame如下所示:

[2] df2
Station ID     a      b       c
8809           46     3       12
8810           36     5       8
8811           NaN    2       7
8812           NaN    NaN     11
8813           82     NaN     15
Run Code Online (Sandbox Code Playgroud)

我遇到的主要问题是列表的长度不同.但是所有列表只包含相同的3个值:a,b和c.它们总是以相同的顺序出现(第一个,第二个,第三个).

以下代码用于工作并返回我想要的内容(df2).

[3] df 
[4] objs = [df, pandas.DataFrame(df['Pollutant Levels'].tolist()).iloc[:, :3]]
[5] df2 = pandas.concat(objs, axis=1).drop('Pollutant Levels', axis=1) …
Run Code Online (Sandbox Code Playgroud)

python dictionary dataframe pandas

93
推荐指数
10
解决办法
5万
查看次数

如何使用 flatten_json 递归地展平嵌套的 JSON

这个问题特定于flatten_jsonGitHub Repo 使用:flatten

  • 该软件包位于 pypi flatten-json 0.1.7 上,可以安装pip install flatten-json
  • 此问题特定于软件包的以下组件:
def flatten_json(nested_json: dict, exclude: list=[''], sep: str='_') -> dict:
    """
    Flatten a list of nested dicts.
    """
    out = dict()
    def flatten(x: (list, dict, str), name: str='', exclude=exclude):
        if type(x) is dict:
            for a in x:
                if a not in exclude:
                    flatten(x[a], f'{name}{a}{sep}')
        elif type(x) is list:
            i = 0
            for a in x:
                flatten(a, f'{name}{i}{sep}')
                i += 1
        else:
            out[name[:-1]] = x

    flatten(nested_json) …
Run Code Online (Sandbox Code Playgroud)

python recursion json pandas

10
推荐指数
1
解决办法
7159
查看次数

如何使用 NaN 对列进行 json_normalize

  • 这个问题特定于a中的数据列pandas.DataFrame
  • 此问题取决于列中的值是否为strdictlisttype。
  • 这个问题解决了在不是有效选项NaN时处理值的问题。df.dropna().reset_index(drop=True)

情况1

  • 对于类型的列,在使用 之前,str必须将列中的值转换为dict类型,使用, 。ast.literal_eval.json_normalize
import numpy as np
import pandas as pd
from ast import literal_eval

df = pd.DataFrame({'col_str': ['{"a": "46", "b": "3", "c": "12"}', '{"b": "2", "c": "7"}', '{"c": "11"}', np.NaN]})

                            col_str
0  {"a": "46", "b": "3", "c": "12"}
1              {"b": "2", "c": "7"}
2                       {"c": "11"}
3                               NaN

type(df.iloc[0, 0])
[out]: str

df.col_str.apply(literal_eval)
Run Code Online (Sandbox Code Playgroud)

错误:

df.col_str.apply(literal_eval) results in ValueError: malformed …
Run Code Online (Sandbox Code Playgroud)

python json dictionary pandas json-normalize

5
推荐指数
1
解决办法
5806
查看次数