我的本地数据帧名称如下:s1_down_threshold
、s1_up_threshold
、s2_down_threshold
、s2_down_threshold
、 s19_down_threshold
、s19_down_threshold
等等。
我想根据一列对名称中包含“down_threshold”的数据帧进行降序排序,并根据同一列对名称中包含“up_threshold”的数据帧进行升序排序。
我知道我可以对其中每一个都使用 .sort_values()
,但我想知道是否有更有效的方法来做到这一点?
我希望得到如下结果:
遍历本地中所有数据帧的名称,然后找到名称中带有“down_threshold”的数据帧并相应地对它们进行排序,然后对“up_threshold”重复相同的过程
编辑1:
最佳答案
您可以在将数据框添加到 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/