Python Panda数据帧排序与月份 [英] Python Panda dataframe sorting with month - year
问题描述
我是python和pandas初学者,并且在groupby操作之后排序数据框时遇到问题。我可以在groupby和count之后得到排序后的数据,但是当我将所有数据放在另一个数据框中时,我没有得到排序数据。
这是我的尝试
conn = sqlite3.connect(' Demo.sqlite')
df = pd.read_sql(SELECT * FROM Table where Column LIKE'x。%',conn)
pf = pd.read_sql(SELECT * FROM表,conn)
df ['DateTime'] = df ['DATE']。apply(lambda x:dt.datetime.fromtimestamp(x).strftime('%b%Y') )
pf ['DateTime'] = pf ['DATE']。apply(lambda x:dt.datetime.fromtimestamp(x).strftime('%b%Y'))
df1 = df.set_index('DateTime',drop = False)
pf1 = pf.set_index('DateTime',drop = False)
df1 = df1.sort(['DateTime '])
pf1 = pf1.sort(['DateTime'])
R1 = df1 ['DateTime'] .groupby(lambda x:x)
R2 = pf1 ['DateTime']。groupby(lambda x:x)
TT = TotalBuild.count() - PrivateBuild.count()
result = pd.DataFrame({'R1':R1 .count(),
'TT':TT,
'R2':R2.count()
})
以下是结果数据框的输出。
I想要按月份排序数据帧。目前数据框按月排序,这就是为什么1月份的所有数据都一起显示的原因。一旦数据被排序,我想绘制条形图。
一种简单的方法是将索引转换为日期,然后转换回每月。
result.index = pd.to_datetime(result.index)
结果。 sort_index(inplace = True)
result.index = monthly_transpose.index.strftime('%B-%Y')
转换为日期时,熊猫将每月的年份转换为每个月的第一个日期,因此可以进行排序。希望它有帮助。
I am a python and pandas beginner and I'm having trouble sorting a data frame after a groupby operation. I can get sorted data after groupby and count but when I put all the data together in another data frame, I dont get sorted data.
Here is my attempt
conn = sqlite3.connect('Demo.sqlite')
df = pd.read_sql("SELECT * FROM Table where Column LIKE 'x.%'", conn)
pf = pd.read_sql("SELECT * FROM Table", conn)
df['DateTime'] = df['DATE'].apply(lambda x: dt.datetime.fromtimestamp(x).strftime('%b %Y'))
pf['DateTime'] = pf['DATE'].apply(lambda x: dt.datetime.fromtimestamp(x).strftime('%b %Y'))
df1 = df.set_index('DateTime', drop=False)
pf1 = pf.set_index('DateTime', drop=False)
df1 = df1.sort(['DateTime'])
pf1 = pf1.sort(['DateTime'])
R1= df1['DateTime'].groupby(lambda x: x)
R2= pf1['DateTime'].groupby(lambda x: x)
TT= TotalBuild.count() - PrivateBuild.count()
result = pd.DataFrame({'R1': R1.count(),
'TT': TT,
'R2': R2.count()
})
Here is output of result data frame.
Check the output of Result data frame here
I want to sort dataframe by month-year. currently data frame is sorted by month, that's why all the data for January is displaying together. once data is sorted i want to draw bar graphs.
One simple way is to just convert the index to date, sort and then convert back to month-year.
result.index = pd.to_datetime(result.index)
result.sort_index(inplace=True)
result.index = monthly_transpose.index.strftime('%B-%Y')
When converting to date, pandas converts the month-year to the first date of each month nad hence the sorting is made possible. Hope it helps.
这篇关于Python Panda数据帧排序与月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!