我习惯于为我所做的任何熊猫操作/更改编写单行代码,而当我回到它之后,我很难阅读/理解(类似于编写一条长的SQL语句。 )。有哪些方法可以提高链接操作的可读性?现在我正在尝试类似的东西:
res = (
# (1) we filter on new__status_group = 'Unknown'
df[df['new__status_group'] == 'UNKNOWN']
# (2) we only care about these two files
[['new__status', 'file_name']]
# (3) group by the new status
.groupby('new__status')
# (4) we want to get the count and value of file_name
.agg({'file_name': 'first', 'new__status': 'size'})
# (5) rename the dummy column we used to grab the count
.rename(columns={'new__status': 'count'})
# (6) sort the values by count desc
.sort_values('count', ascending=False)
# (7) now that we're all good, reset the index so its like a normal data frame with all the fields
.reset_index()
# (8) limit to the top ten
.head(10)
# (9) and finally we want to pass it as a list of records (dict) for the end usage
.to_dict('records')
)
这是一个好风格吗?还是这种方式过于笨拙和冗长?还有什么其他方法可以提高熊猫函数的可读性?
答案 0 :(得分:2)
两个改进,首先使用loc
而不是链片,第二个agg
可以传递名称,因此您不需要rename
res = (
df.loc[df['new__status_group'] == 'UNKNOWN', ['new__status', 'file_name']]
.groupby('new__status')
.agg(file_name=('file_name','first'), count=('new__status', 'size'))
.sort_values('count', ascending=False)
.reset_index()
.head(10)
.to_dict('records')
)