Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将项目is字典转换为数据框架中的新列?_Python_Json_Pandas_Dataframe_Dictionary - Fatal编程技术网

Python 如何将项目is字典转换为数据框架中的新列?

Python 如何将项目is字典转换为数据框架中的新列?,python,json,pandas,dataframe,dictionary,Python,Json,Pandas,Dataframe,Dictionary,方法1:我已经用pandas读取了json文件,我手里拿着一个数据框,但是正如您在pic(链接)中看到的,元素本身是dict的某些列,我如何在当前数据框中使用dict as列的键以及相应的值创建列 方法2:我附加了另一个图像,在这里我使用“with open”读取了文件,因此它将是一个列表,然后使用json.normalize()转换为pandas数据帧。当我使用它时,我可以很容易地得到我想要的 那么,在使用方法1时,如何使用新列转换数据帧? 请看两幅图中的“类型”栏,了解我的意思? 附言:我没

方法1:我已经用pandas读取了json文件,我手里拿着一个数据框,但是正如您在pic(链接)中看到的,元素本身是dict的某些列,我如何在当前数据框中使用dict as列的键以及相应的值创建列

方法2:我附加了另一个图像,在这里我使用“with open”读取了文件,因此它将是一个列表,然后使用json.normalize()转换为pandas数据帧。当我使用它时,我可以很容易地得到我想要的

那么,在使用方法1时,如何使用新列转换数据帧? 请看两幅图中的“类型”栏,了解我的意思? 附言:我没有足够的徽章来张贴这张照片


感谢您提前回复

首先,您有这样一个df:

我认为您应该按原样为“key”列创建一个def():

def item_x (row, column, key) :
    x = row[column][key]
    return x

然后,您可以创建新列,比如“id\u type”和“name\u type”(对于数据帧的“type”列:

# create new column with the dict values
df['id_type'] = df.apply (lambda row: item_x (row, 'type', 'id'),axis=1)
df['name_type'] = df.apply (lambda row: item_x (row, 'type', 'name'),axis=1)
最后,如果需要,请删除“类型”列:

df = df.drop('type', axis=1)
最后你有:

首先,您有这样一个df:

我认为您应该按原样为“key”列创建一个def():

def item_x (row, column, key) :
    x = row[column][key]
    return x

然后,您可以创建新列,比如“id\u type”和“name\u type”(对于数据帧的“type”列:

# create new column with the dict values
df['id_type'] = df.apply (lambda row: item_x (row, 'type', 'id'),axis=1)
df['name_type'] = df.apply (lambda row: item_x (row, 'type', 'name'),axis=1)
最后,如果需要,请删除“类型”列:

df = df.drop('type', axis=1)
最后你有:

不发布图片。发布数据和预期输出不发布图片。发布数据和预期输出