![](/img/trans.png)
[英]How to sort column names in pandas dataframe by specifying keywords
[英]Sort pandas dataframe by column specifying custom order
我得到了一个看起来像这样的 csv:
col1, col2, col3, col4
txt,txt,error,txt
txt,txt,new,txt
txt,txt,new,txt
txt,txt,error,txt
txt,txt,new,txt
txt,txt,fix,txt
我想将行的顺序更改为此
col1, col2, col3, col4
txt,txt,new,txt
txt,txt,new,txt
txt,txt,new,txt
txt,txt,fix,txt
txt,txt,error,txt
txt,txt,error,txt
所以行跟随新闻 -> 更改 -> col3 中的错误
到目前为止,尝试了不同的东西:
import pandas as pd
csv_dataframe = pd.read_csv(user_submitted_csv_file)
csv_dataframe = csv_dataframe.sort_values(by=['col3'])
但这还不够,因为它不是按字母顺序排列的,也不是升序/降序的。 还尝试了诸如提取行-> 删除所有行-> 按正确顺序添加回来之类的方法,但也遇到了问题...
从pandas>=1.1.0
您可以使用.sort_values
方法的key
参数来编写定义您喜欢的自定义顺序的 lambda 函数。
要做到这一点,您只需要按照您想要的顺序定义一个自定义字典
custom_dict = {'new': 0, 'fix': 1, 'error': 2}
df.sort_values(by=['col3'], key=lambda x: x.map(custom_dict))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.