pandas df 将两列转换为字典格式

修改df 列名

import pandas as pd
import json

data = {
    'keys': ['a', 'b', 'c', 'd'],
    'values': [1, 2, 3, 4]
}

columns_mapping = {'keys': 'keys11', 'values': 'values'}
df = pd.DataFrame(data)
df = df.rename(columns=columns_mapping)

print(df.columns)

修改DF 列名 

import pandas as pd

data = {
    'keys': ['a', 'b', 'c', 'd'],
    'values': [1, 2, 3, 4]
}

columns_mapping = ['keys11', 'values']
df = pd.DataFrame(data, columns=columns_mapping)

print(df.columns)

两个转换为字典

import pandas as pd

data = {
    'keys': ['a', 'b', 'c', 'd'],
    'values': [1, 2, 3, 4]
}
df = pd.DataFrame(data)
# # 使用zip和dict函数将两列转换为字典
result_dict = dict(zip(df['keys'], df['values']))
print(result_dict)

 

posted @ 2024-03-01 11:09  yongqi-911  阅读(336)  评论(0编辑  收藏  举报