有什么方法可以从DataFrame.from_dict中删除列号和行号? [英] Is there any way to remove column and rows numbers from DataFrame.from_dict?
问题描述
因此,我的字典中的数据框存在问题-python实际上用数字命名我的行和列。
这是我的代码:
So, I have a problem with my dataframe from dictionary - python actually "names" my rows and columns with numbers. Here's my code:
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'])
,但这给了我一个错误:
I've tried to rename columns like this:
dataframe=pd.DataFrame.from_dict(sorted_by_value, orient='index', columns=['A', 'B', 'C'])
, but it gives me a error:
AttributeError: 'list' object has no attribute 'values'
有什么办法可以解决?
Is there any way to fix it?
编辑:
这是数据框的第一部分:
Here's the first part of my data frame:
0 1
0 VW 1383
1 AUDI 1053
2 VOLVO 789
3 BMW 749
4 OPEL 621
5 MERCEDES BENZ 593
...
第1行和第1列正是我要删除/重命名的内容
The 1st rows and columns are exactly what I need to remove/rename
推荐答案
索引
和列
是数据框的属性
只要 len(df.index)> 0
和 len(df.columns)> 0
,即您的数据框具有非零行和非零列,您无法摆脱 pd.DataFrame
对象中的标签。
index
and columns
are properties of your dataframe
As long as len(df.index) > 0
and len(df.columns) > 0
, i.e. your dataframe has nonzero rows and nonzero columns, you cannot get rid of the labels from your pd.DataFrame
object. Whether the dataframe is constructed from a dictionary, or otherwise, is irrelevant.
可以要做的就是将它们从表示形式中删除。
What you can do is remove them from a representation of your dataframe, with output either as a Python str
object or a CSV file. Here's a minimal example:
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)
这篇关于有什么方法可以从DataFrame.from_dict中删除列号和行号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!