python - 有没有办法从 DataFrame.from_dict 中删除列号和行号?
问题描述
所以,我的字典中的数据框有问题——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'])
,但它给了我一个错误:
AttributeError: 'list' object has no attribute 'values'
有什么办法可以解决吗?
编辑: 这是我的数据框的第一部分:
0 1
0 VW 1383
1 AUDI 1053
2 VOLVO 789
3 BMW 749
4 OPEL 621
5 MERCEDES BENZ 593
...
第一行和第一列正是我需要删除/重命名的
解决方案
index
并且columns
是您的数据框的属性
只要len(df.index) > 0
and len(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)
推荐阅读
- excel - 在Visual Basic中从位置到结尾删除字符串的一部分
- spring - 向 Spring Boot 应用程序添加网关功能
- javascript - Angular 自动转义 HTML
- dockerfile - yaml:第 8 行:没有找到预期的密钥
- c - 警告:从不兼容的指针类型 const int (*)[3] 分配给 int **
- python - 使用 PyPy 时 DeepCopy 很慢
- python - 在python中使用for循环迭代的有序多线程
- vue.js - vuejs中的分页?
- ios - 选择器值到 tableView swift
- javascript - 无法使用 XPath 将文本从节点中取出