如何使用matplotlib.pyplot绘制列表?

时间:2018-07-15 13:35:52

标签: python

为什么会出现TypeError: unhashable type: numpy.ndarray错误?另外,我不记得numpy.ndarray在做什么将numpy导入代码中?错误出现在代码的最后一行

import pandas as pd
import matplotlib.pyplot as plt

entries_csv = "C:\\Users\\Asus\\Desktop\\Entries.csv"
listofaccounts_csv = "C:\\Users\\Asus\\Desktop\\List of Accounts.csv"

data_entries = pd.read_csv(entries_csv)
data_listofaccounts = pd.read_csv(listofaccounts_csv)

i = 0
summary_name = [0]*len(data_listofaccounts)
summary =  [0]*1*len(data_listofaccounts)
for account_name in data_listofaccounts['Account Name']:
    summary_name[i] = account_name
    for debit_account in data_entries['DEBIT ACCOUNT']:
        if account_name == debit_account:
            summary[i] += data_entries['DEBIT AMOUNT']
    i += 1


plt.bar(list(summary_name), list(summary))

这些是数据:

1。)条目:

enter image description here

2。)帐户列表:

enter image description here

基本上,我想对帐户列表中的每个项目进行汇总,以总结每种帐户类型的所有借方金额

1 个答案:

答案 0 :(得分:1)

我认为在这种情况下,您确实要在两个数据帧之间利用pd.merge功能。参见此处:https://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.DataFrame.merge.html。加入两个表后,您要根据“帐户名”进行分组并执行汇总。例如:

list_of_accounts_df = pd.DataFrame({
    'Account Name': ['ACCOUNT PAYABLE', 'OUTSIDE SERVICE'], 
    'Type': ['CURRENT LIABILITY', 'EXPENSE']
})

entries_df = pd.DataFrame({
    'DEBIT ACCOUNT':['OUTSIDE SERVICE', 'OUTSIDE SERVICE'], 
    'DEBIT AMOUNT': [46375.8, 42091.42] ,
    'CREDIT ACCOUNT':['CASH IN BANK', 'CASH ON HAND'],
    'CREDIT AMOUNT':[46375.8, 42091.42]
})


pd.merge(list_of_accounts_df, entries_df, left_on='Account Name', right_on='DEBIT ACCOUNT', how='left').fillna(0).groupby('Account Name')['DEBIT AMOUNT'].sum()

输出变为一个系列,其中每个索引为“帐户名称”,该值为该系列所有借方金额的总和。因此,在这种情况下:

Account Name
ACCOUNT PAYABLE    0.00    
OUTSIDE SERVICE    88467.22

然后关于如何绘制它的问题,对于条形图,您不能直接提供x轴或y轴的字符串值。

使用以下示例:https://pythonspot.com/matplotlib-bar-chart/,在我们的示例中,您可以这样做:

objects = x.index.values 
y_pos = range(len(objects)
vals = x.values

plt.bar(y_pos, vals, align='center')
plt.xticks(y_pos, objects)
plt.ylabel('Sum of Debits')
plt.title('Total Debits Per Account')

plt.show()

在我们的简单示例中给出了以下内容:

Sum of debits for all accounts