我正在尝试创建一个Pandas dataFrame,以便我可以使用ggPlot创建一些可视化。但我很难获得DataFrame结构设置。
我的可视化将是(年与总数)的线图。线图将多年来跟踪多个'cause_of_death'。
我导入了我的CSV文件,按年份分组,然后是'cause_of_death'并进行计数。但是创建一个线图并不是正确的格式,因为它不是一个DataFrame。
以下是我的代码;任何建议都会有所帮助,谢谢。
我想从CSV文件中找到的字段是'deathYear'和'cause_of_death'
from pandas import *
from ggplot import *
df = pandas.read_csv('query_result.csv')
newDF = df.loc[:,['date_of_death_year','acme_underlying_cause_code']]
data = DataFrame(newDF.groupby(['date_of_death_year','acme_underlying_cause_code']).size())
print data
答案 0 :(得分:1)
这是一个很大的问题,但解决起来非常简单。 (提示,它与ggplot
无关。它是关于pandas
如何工作的全部)
以下是我如何呈现您的代码:
import numpy as np # |Don't import * from these
import pandas as pd # |
from ggplot import * # But this is customary because it's like R
# All this bit is just to make a DataFrame
# You can ignore it all
causes = ['foo', 'bar', 'baz']
years = [2001, 2002, 2003, 2004]
size = 100
data = {'causes':np.random.choice(causes, size),
'years':np.random.choice(years, size),
'something_else':np.random.random(size)
}
df = pd.DataFrame(data)
# Here's where the good stuff happens. You're importing from
# a CSV so you can just start here
counts = df.groupby(['years', 'causes'])['something_else'].count()
counts = counts.reset_index() # Because ggplot doesn't plot with indexes
g = ggplot(counts, aes(x='years', y='something_else', color='causes')) +\
geom_line()
print(g)
导致: