python - Pandas DataFrame 中的 JSON 对象

标签 python json pandas dataframe

我在 pandas 数据框列中有一个 JSON 对象,我想将其拆开并放入其他列中。在数据框中,JSON 对象看起来像一个包含字典数组的字符串。数组可以是可变长度的,包括零,或者列甚至可以为空。我已经编写了一些代码,如下所示,它可以满足我的要求。列名由两个部分构成,第一个是字典中的键,第二个是字典中键值的子字符串。

此代码运行正常,但在大数据帧上运行时速度非常慢。谁能提供一种更快(也可能更简单)的方法来做到这一点?另外,如果您看到一些不合理/高效/pythonic 的东西,请随意挑出我所做的漏洞。我仍然是一个相对初学者。非常感谢。

# Import libraries 
import pandas as pd
from IPython.display import display # Used to display df's nicely in jupyter notebook.
import json

# Set some display options
pd.set_option('max_colwidth',150)

# Create the example dataframe
print("Original df:")
df = pd.DataFrame.from_dict({'ColA': {0: 123, 1: 234, 2: 345, 3: 456, 4: 567},\
 'ColB': {0: '[{"key":"keyValue=1","valA":"8","valB":"18"},{"key":"keyValue=2","valA":"9","valB":"19"}]',\
  1: '[{"key":"keyValue=2","valA":"28","valB":"38"},{"key":"keyValue=3","valA":"29","valB":"39"}]',\
  2: '[{"key":"keyValue=4","valA":"48","valC":"58"}]',\
  3: '[]',\
  4: None}})
display(df)

# Create a temporary dataframe to append results to, record by record
dfTemp = pd.DataFrame()

# Step through all rows in the dataframe
for i in range(df.shape[0]):
    # Check whether record is null, or doesn't contain any real data
    if pd.notnull(df.iloc[i,df.columns.get_loc("ColB")]) and len(df.iloc[i,df.columns.get_loc("ColB")]) > 2:
        # Convert the json structure into a dataframe, one cell at a time in the relevant column
        x = pd.read_json(df.iloc[i,df.columns.get_loc("ColB")])
        # The last bit of this string (after the last =) will be used as a key for the column labels
        x['key'] = x['key'].apply(lambda x: x.split("=")[-1])
        # Set this new key to be the index
        y = x.set_index('key')
        # Stack the rows up via a multi-level column index
        y = y.stack().to_frame().T
        # Flatten out the multi-level column index
        y.columns = ['{1}_{0}'.format(*c) for c in y.columns]
        # Give the single record the same index number as the parent dataframe (for the merge to work)
        y.index = [df.index[i]]
        # Append this dataframe on sequentially for each row as we go through the loop
        dfTemp = dfTemp.append(y)

# Merge the new dataframe back onto the original one as extra columns, with index mataching original dataframe
df = pd.merge(df,dfTemp, how = 'left', left_index = True, right_index = True)

print("Processed df:")
display(df)

最佳答案

首先,关于 pandas 的一般建议。 如果您发现自己遍历数据框的行,很可能是您做错了。

考虑到这一点,我们可以使用 pandas 的“apply”方法重写您当前的过程(这可能会加快速度,因为这意味着 df 上的索引查找要少得多):

# Check whether record is null, or doesn't contain any real data
def do_the_thing(row):
    if pd.notnull(row) and len(row) > 2:
        # Convert the json structure into a dataframe, one cell at a time in the relevant column
        x = pd.read_json(row)
        # The last bit of this string (after the last =) will be used as a key for the column labels
        x['key'] = x['key'].apply(lambda x: x.split("=")[-1])
        # Set this new key to be the index
        y = x.set_index('key')
        # Stack the rows up via a multi-level column index
        y = y.stack().to_frame().T
        # Flatten out the multi-level column index
        y.columns = ['{1}_{0}'.format(*c) for c in y.columns]

        #we don't need to re-index
            # Give the single record the same index number as the parent dataframe (for the merge to work)
            #y.index = [df.index[i]]
        #we don't need to add to a temp df
        # Append this dataframe on sequentially for each row as we go through the loop
        return y.iloc[0]
    else:
        return pd.Series()
df2 = df.merge(df.ColB.apply(do_the_thing), how = 'left', left_index = True, right_index = True)

请注意,这将返回与之前完全相同的结果,我们没有更改逻辑。 apply 方法对索引进行排序,所以我们可以合并,很好。

我相信这可以从加快速度和更加地道的角度回答您的问题。

不过,我认为您应该考虑,您想用这个数据结构做什么,以及如何更好地构建您正在做的事情。

鉴于 ColB 可以是任意长度,您最终会得到一个包含任意列数的数据框。当您出于任何目的访问这些值时,无论目的是什么,这都会给您带来痛苦。

ColB 中的所有条目都重要吗?你可以只保留第一个吗?您需要知道某个 valA val 的索引吗?

这些是你应该问自己的问题,然后决定一个结构,它可以让你做任何你需要的分析,而不必检查一堆随意的东西。

关于python - Pandas DataFrame 中的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45687723/

相关文章:

python - 无法通过在 python 3.4 上运行的 pip 安装模块

python - json-> csv 使用 in2csv - 指定键不返回任何值

json - 嵌套 JSON 中的相同结构

javascript - 分机 JS 4 : Convert JSON object to another JSON object using JavaScript

python - 使用距缺失值最近日期的值填充缺失值

python - matplotlib:在轴上绘制一个框

Python 将 datetime.time 转换为箭头

深度学习环境下Python包安装错误

python - django 的 URL Conf 支持将参数映射到字符串吗?

pandas - 类型错误 : field Customer: Can not merge type <class 'pyspark.sql.types.StringType' > and <class 'pyspark.sql.types.DoubleType' >