有什么方法可以从中删除列和行号吗数据帧。来自于?dict?

2024-10-04 11:33:18 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我在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']),但它给了我一个错误:

^{pr2}$

有办法解决吗?在

编辑: 这是我的数据框架的第一部分:

                     0     1
0                   VW  1383
1                 AUDI  1053
2                VOLVO   789
3                  BMW   749
4                 OPEL   621
5        MERCEDES BENZ   593
...

第一行和第一列正是我需要删除/重命名的内容


Tags: infromnumberdataframeforbyvaluedict
2条回答

indexcolumns是dataframe

的属性

只要len(df.index) > 0len(df.columns) > 0,也就是说,你的数据帧有非零行和非零列,你就不能从你的pd.DataFrame对象中去掉标签。不管数据帧是从字典构造的,还是从其他方面构造的,都无关紧要。在

您可以从数据帧的表示中删除它们,输出为Pythonstr对象或CSV文件。下面是一个最小的例子:

df = pd.DataFrame([[1, 2, 3], [4, 5, 6]])

print(df)
#    0  1  2
# 0  1  2  3
# 1  4  5  6

# output to string without index or headers
print(df.to_string(index=False, header=False))
# 1  2  3
# 4  5  6

# output to csv without index or headers
df.to_csv('file.csv', index=False, header=False)

通过对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,然后可以使用dataframe.columns = [list, of, column, headings]重命名其列。对于索引,请查看pd.DataFrame.set_index(drop=True)docs)和{}(docs)。在

相关问题 更多 >