pandas两列转换成字典的健和值
Pandas to Dict
两列转换成字典的key和value
df:
name | age |
---|---|
Mary | 26 |
Sellina | 28 |
Zaca | 27 |
想将name这列变成字典的健,年龄对应成字典的值,健值对应如下:
{‘Mary’:26,‘Sellina’:28,‘Zaca’:27}
import pandas as pd
import pandas as pd
a = ['Mary','Sellina','Zaca']
b = [26,28,27]
data = {'name':a,'age':b}
df = pd.DataFrame(data)
print(df)
结果如下:
name age
0 Mary 26
1 Sellina 28
2 Zaca 27
python代码实现转换成字典:
df1 = df.set_index(['name'])['age'].to_dict()
print(df1)
结果如下:
{'Mary': 26, 'Sellina': 28, 'Zaca': 27}
列名变成字典的key
df2 = df.to_dict(orient = 'list')
结果如下:
{'name': ['Mary', 'Sellina', 'Zaca'], 'age': [26, 28, 27]}