如果 '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:
(key, value)
tuple.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.