所以,我在dictionary中的dataframe出现了一个问题——python实际上用数字“命名”了我的行和列。 我的代码是:
a = dict()
dfList = [x for x in df['Marka'].tolist() if str(x) != 'nan']
dfSet = set(dfList)
dfList123 = list(dfSet)
for i in range(len(dfList123)):
number = dfList.count(dfList123[i])
a[dfList123[i]]=number
sorted_by_value = sorted(a.items(), key=lambda kv: kv[1], reverse=True)
dataframe=pd.DataFrame.from_dict(sorted_by_value)
print(dataframe)
我尝试过像这样重命名列:
dataframe=pd.DataFrame.from_dict(sorted_by_value, orient='index', columns=['A', 'B', 'C'])
,但它给了我一个错误:
有办法解决吗?在
编辑: 这是我的数据框架的第一部分:
0 1
0 VW 1383
1 AUDI 1053
2 VOLVO 789
3 BMW 749
4 OPEL 621
5 MERCEDES BENZ 593
...
第一行和第一列正是我需要删除/重命名的内容
的属性index
和columns
是dataframe只要
len(df.index) > 0
和len(df.columns) > 0
,也就是说,你的数据帧有非零行和非零列,你就不能从你的pd.DataFrame
对象中去掉标签。不管数据帧是从字典构造的,还是从其他方面构造的,都无关紧要。在您可以从数据帧的表示中删除它们,输出为Python
str
对象或CSV文件。下面是一个最小的例子:通过对
dict_items
对象(a.items()
)进行排序,您已经创建了一个列表。 您可以用type(sorted_by_value)
来检查。然后,当您尝试使用pd.DataFrame.from_dict()
方法时,它失败了,因为它需要一个字典,它有“values”,但却收到了一个列表。在对代码的最小修复可能是替换以下行:
dataframe=pd.DataFrame.from_dict(sorted_by_value)
有:
dataframe = pd.DataFrame(dict(sorted_by_value), index=[0])
。在(此处需要}被转换为
index=[0]
参数,因为pd.DataFrame
要求字典的格式为{'key1': [list1, of, values], 'key2': [list2, of, values]}
,而{{'key1': value1, 'key2': value2}
。)另一个选择是使用
pd.DataFrame(sorted_by_value)
直接从排序的项目生成一个数据帧,尽管您可能需要调整sorted_by_value
或结果以获得所需的数据帧格式。在或者,查看
collections.OrderedDict
(文档是here),以避免排序到列表,然后再转换回字典。在编辑
关于列和索引的命名,如果没有看到数据/期望的结果,很难给出具体的建议。上面的选项将允许删除错误并允许您创建一个dataframe,然后可以使用}(docs)。在
dataframe.columns = [list, of, column, headings]
重命名其列。对于索引,请查看pd.DataFrame.set_index(drop=True)
(docs)和{相关问题 更多 >
编程相关推荐