python - 如何搜索数据框并相应地对每个数据框进行排序?

标签 python python-3.x pandas

我的本​​地数据帧名称如下:s1_down_thresholds1_up_thresholds2_down_thresholds2_down_threshold s19_down_thresholds19_down_threshold 等等。

我想根据一列对名称中包含“down_threshold”的数据帧进行降序排序,并根据同一列对名称中包含“up_threshold”的数据帧进行升序排序。

我知道我可以对其中每一个都使用 .sort_values(),但我想知道是否有更有效的方法来做到这一点?

我希望得到如下结果:

遍历本地中所有数据帧的名称,然后找到名称中带有“down_threshold”的数据帧并相应地对它们进行排序,然后对“up_threshold”重复相同的过程

编辑1:

enter image description here

最佳答案

您可以在将数据框添加到 Dataframe 字典之前对其进行命名,如下所示:

import numpy as np
import pandas as pd
import json

#using sample data

data = {'id': ['A', 'B', 'C', 'D'], 'value': [2000, 600, 400, 3000]}

df=pd.DataFrame(data)
df1 =df.copy()
df2=df.copy()
df3=df.copy()
df4=df.copy()

DataFrameDict=[]

df1.name='s1_down_threshold'
DataFrameDict.append(df1)
df2.name='s2_down_threshold'
DataFrameDict.append(df2)
df3.name='s1_up_threshold'
DataFrameDict.append(df3)
df4.name='s2_up_threshold'
DataFrameDict.append(df4)

for i in range(len(DataFrameDict)):
    if ('down' in DataFrameDict[i].name):
        print (DataFrameDict[i].name,'sorted down')
        DataFrameDict[i].sort_values(by='value', ascending=False,inplace=True)
    elif ('up' in DataFrameDict[i].name):
        print (DataFrameDict[i].name,'sorted up')
        DataFrameDict[i].sort_values(by='value', ascending=True,inplace=True)

>>> DataFrameDict
[  id  value
3  D   3000
0  A   2000
1  B    600
2  C    400,   
   id  value
3  D   3000
0  A   2000
1  B    600
2  C    400,   
   id  value
2  C    400
1  B    600
0  A   2000
3  D   3000,   
   id  value
2  C    400
1  B    600
0  A   2000
3  D   3000]

关于python - 如何搜索数据框并相应地对每个数据框进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56394247/

相关文章:

python - 在Python中记录未使用MySQL连接器插入

python - 无法在 Python 中保留编码文本

python - static_url_path和变量规则

Python:检测输入仅适用于 1 个字符长的字符串

python - 更快地向前填充和向后填充 groupby

要列出的 Python 范围

python - Python 2.7 和 3.6 之间的不同 @patch 行为(使用 mock)

python-3.x - 如何在自制的PyQt GUI中嵌入 'QScintilla'代码编辑器?

python - Pandas 数据框列,其中包含不同列长度不同的列表列表

python-2.7 - Pandas 与前一天的价格变化率差异