简体   繁体   中英

How to create a new column from existed column which is formatted like a dictionary pandas dataframe

In my pandas dataframe, I have a column formatted like a dictionary:

在此处输入图像描述

What I want to do is extract data from this column and add two columns like this:

在此处输入图像描述

In other words, I want to separate values between ":".

I wonder if there is an easy way to do this?

如果 'column1' 只包含一个键:每个字典的值,那么您可以通过调用 items 方法并使用第一个元组来添加新列:

df[['column2', 'column3']] = pd.DataFrame(df['column1'].apply(lambda x: list(x.items())[0]).tolist(), index=df.index)

Assuming all values in df.column1 are JSON-formatted strings containing a single key:

  1. Parse each row as JSON.
  2. Convert each row to a (key, value) tuple.
  3. Create new DataFrame with 2 columns from the list of 2-tuples.
import json
import pandas as pd


df = pd.DataFrame(
    ['{"x": 1}', '{"y": 2}', '{"z": 3}'],
    columns=["column1"],
)
df2 = pd.DataFrame(
    df.column1.map(lambda x: json.loads(x).popitem()).tolist(),
    columns=["column2", "column3"],
)

print(df)
print(df2)

Output

    column1
0  {"x": 1}
1  {"y": 2}
2  {"z": 3}
  column2  column3
0       x        1
1       y        2
2       z        3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM