我正在尝试将字典列表保存到熊猫数据框的每个单元格中。虽然我可以在运行脚本时与它们交互并将它们保存到CSV中,但我不确定是否有一种方法可以在之后加载CSV,并将每个单元格中的字符串作为字典列表读取。例如:
obj1 = {'number': 22, 'popularity': 12, 'attr3': "cows"}
obj2 = {'number': 99, 'popularity': 4, 'attr3': "dogs"}
obj3 = {'number': 21, 'popularity': 0, 'attr3': "cats"}
tmp_list_1= [obj1,obj2,obj3]
tmp_list_2= [obj2,obj2,obj2]
tmp_list_3= [obj3,obj3,obj3]
list_of_lists = [tmp_list_1,tmp_list_2,tmp_list_3]有了这些列表,我就可以创建一个熊猫数据框了。
df = pd.DataFrame([list_of_lists,list_of_lists,list_of_lists])这个数据框中的所有单元格都包含列表,并且这些列表+其中包含的字典保留了它们的属性(即,列表的行为类似于列表-我可以遍历它们)。
然后,我将此数据帧保存到CSV。
df.to_csv("testing_list_dicts_import.csv")可以理解的是,单元格的值在通过
tmp_import = pd.read_csv("testing_list_dicts_import.csv")我想知道的是,是否有一种方法可以将这些单元格导入而不是作为字符串,而是作为对象列表。
非常感谢您的帮助!
编辑:在下面添加CSV:
,0,1,2
0,"[{'popularity': 12, 'number': 22, 'attr3': 'cows'}, {'popularity': 4, 'number': 99, 'attr3': 'dogs'}, {'popularity': 0, 'number': 21, 'attr3': 'cats'}]","[{'popularity': 4, 'number': 99, 'attr3': 'dogs'}, {'popularity': 4, 'number': 99, 'attr3': 'dogs'}, {'popularity': 4, 'number': 99, 'attr3': 'dogs'}]","[{'popularity': 0, 'number': 21, 'attr3': 'cats'}, {'popularity': 0, 'number': 21, 'attr3': 'cats'}, {'popularity': 0, 'number': 21, 'attr3': 'cats'}]"
1,"[{'popularity': 12, 'number': 22, 'attr3': 'cows'}, {'popularity': 4, 'number': 99, 'attr3': 'dogs'}, {'popularity': 0, 'number': 21, 'attr3': 'cats'}]","[{'popularity': 4, 'number': 99, 'attr3': 'dogs'}, {'popularity': 4, 'number': 99, 'attr3': 'dogs'}, {'popularity': 4, 'number': 99, 'attr3': 'dogs'}]","[{'popularity': 0, 'number': 21, 'attr3': 'cats'}, {'popularity': 0, 'number': 21, 'attr3': 'cats'}, {'popularity': 0, 'number': 21, 'attr3': 'cats'}]"
2,"[{'popularity': 12, 'number': 22, 'attr3': 'cows'}, {'popularity': 4, 'number': 99, 'attr3': 'dogs'}, {'popularity': 0, 'number': 21, 'attr3': 'cats'}]","[{'popularity': 4, 'number': 99, 'attr3': 'dogs'}, {'popularity': 4, 'number': 99, 'attr3': 'dogs'}, {'popularity': 4, 'number': 99, 'attr3': 'dogs'}]","[{'popularity': 0, 'number': 21, 'attr3': 'cats'}, {'popularity': 0, 'number': 21, 'attr3': 'cats'}, {'popularity': 0, 'number': 21, 'attr3': 'cats'}]"发布于 2018-03-05 03:49:19
回答你的问题,no。
这是因为python无法自行判断文件中的文本实际上是代码还是字符串。为了安全起见,它以字符串的形式读取文件中的所有内容。
但是,如果.csv中的数据与代码中的数据完全相同,即如果.csv中的数据看起来像x, y, z etc.,那么在从文件中读取字符串以将其解析为代码时,可以使用eval()。
发布于 2018-03-05 05:10:36
设计一个需要使用eval甚至ast.literal_eval来读取csv文件内容的工作流不是一个好的实践。您提出的解决方案也将是低效的。
对于您的特定问题,您应该分别存储字典和映射。存储包含整数指针和单独字典的数据帧。当您需要提取给定指针n的特定字典时,只需使用d[n]。
下面是一个示例:
import pandas as pd
d = {1: {'number': 22, 'popularity': 12, 'attr3': "cows"},
2: {'number': 99, 'popularity': 4, 'attr3': "dogs"},
3: {'number': 21, 'popularity': 0, 'attr3': "cats"}}
tmp_list_1 = [1, 2, 3]
tmp_list_2 = [2, 2, 2]
tmp_list_3 = [3, 3, 3]
LoL = [tmp_list_1, tmp_list_2, tmp_list_3]
df = pd.DataFrame(LoL, columns=['col1', 'col2', 'col3'])
# col1 col2 col3
# 0 1 2 3
# 1 2 2 2
# 2 3 3 3https://stackoverflow.com/questions/49099577
复制相似问题