我的数据框df就像:
col_1 col_2 col_3
A Product 1
B product 2
C Offer 1
D Product 1
我想要的是将所有此列转换为json,条件是col_2和col_1的行应为键值对。我尝试了以下方法:
df['col_1_2'] = df.apply(lambda row: {row['col_2']:row['col_1']}, axis=1)
df['final_col']=df[['col_1_2','col_3']].to_dict('r')
我的df ['final_col']的第一行是:
{'col_1_2': {'product': A}, 'value': 1.0},
但是我想要的是:
{'product': A, 'value': 1.0}
答案 0 :(得分:3)
添加缺失键,其值为col_3
:
df['final_col'] = df.apply(lambda row: {row['col_2']:row['col_1'], 'value':row['col_3']},
axis=1)
print (df)
col_1 col_2 col_3 final_col
0 A Product 1 {'Product': 'A', 'value': 1}
1 B product 2 {'product': 'B', 'value': 2}
2 C Offer 1 {'Offer': 'C', 'value': 1}
3 D Product 1 {'Product': 'D', 'value': 1}
如果需要在列表中输出:
L = [{b:a, 'value':c} for a,b,c in zip(df['col_1'], df['col_2'], df['col_3'])]
print (L)
[{'Product': 'A', 'value': 1},
{'product': 'B', 'value': 2},
{'Offer': 'C', 'value': 1},
{'Product': 'D', 'value': 1}]
或json
:
import json
j = json.dumps([{b:a, 'value':c} for a,b,c in zip(df['col_1'], df['col_2'], df['col_3'])])
print (j)
[{"Product": "A", "value": 1},
{"product": "B", "value": 2},
{"Offer": "C", "value": 1},
{"Product": "D", "value": 1}]