首页 > 解决方案 > 有没有办法从 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
...

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

标签: pythonpython-3.xpandasdataframeseries

解决方案


index并且columns是您的数据框的属性

只要len(df.index) > 0and 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)

推荐阅读