如何将字典中的列表转为字符串并放入DataFrame独立列?
解决字典列表值转字符串并生成DataFrame的问题
问题背景
我有一个值为列表的字典:
my_dict = {1: ['Home', 'Stories'], 2: ['Sounds', 'Stories', 'Home', 'Home', 'Stories'], 3: ['Journeys / Series', 'Journeys / Series', 'Journeys / Series'], 4: [ 'Home', 'Home', 'Home'], 5: ['Home', 'Stories', 'Home', 'Home', 'Home', 'Cancellation Flow'], 6: ['My Account', 'My Account']}
我希望将字典中的列表转换为字符串,并放入独立的列中。
我尝试了以下代码,但因为字典的值是列表,没得到预期结果:
keys_list = list(my_dict.keys()) values_list = list(my_dict.values()) df_keyvalues = pd.DataFrame({'Column1': keys_list, 'Column2': values_list}) df_keyvalues
期望的输出格式如下:
User List 1 'Home', 'Stories' 2 'Sounds', 'Stories', 'Home', 'Home', 'Stories' 3 'Journeys / Series', 'Journeys / Series', 'Journeys / Series' 4 'Home', 'Home', 'Home' 5 'Home', 'Stories', 'Home', 'Home', 'Home', 'Cancellation Flow' 6 'My Account', 'My Account'
解决方案
只需把字典里的每个列表转换成指定格式的字符串,再构建DataFrame即可,代码如下:
import pandas as pd my_dict = {1: ['Home', 'Stories'], 2: ['Sounds', 'Stories', 'Home', 'Home', 'Stories'], 3: ['Journeys / Series', 'Journeys / Series', 'Journeys / Series'], 4: [ 'Home', 'Home', 'Home'], 5: ['Home', 'Stories', 'Home', 'Home', 'Home', 'Cancellation Flow'], 6: ['My Account', 'My Account']} # 将每个列表转为带单引号的字符串格式 processed_dict = {k: ", ".join(f"'{item}'" for item in v) for k, v in my_dict.items()} # 构建DataFrame并指定列名 df = pd.DataFrame(list(processed_dict.items()), columns=['User', 'List']) print(df)
运行后输出与预期一致:
User List 0 1 'Home', 'Stories' 1 2 'Sounds', 'Stories', 'Home', 'Home', 'Stories' 2 3 'Journeys / Series', 'Journeys / Series', 'Journeys / Series' 3 4 'Home', 'Home', 'Home' 4 5 'Home', 'Stories', 'Home', 'Home', 'Home', 'Cancellation Flow' 5 6 'My Account', 'My Account'
代码说明
", ".join(f"'{item}'" for item in v):遍历列表内的每个元素,给元素添加单引号后,用逗号加空格拼接成完整字符串。pd.DataFrame(list(processed_dict.items()), columns=['User', 'List']):将处理后的字典转为键值对列表,指定列名生成目标DataFrame。
内容的提问来源于stack exchange,提问作者Sophie Martusewicz
相关产品推荐
相关产品推荐

