将排序应用于数据帧列表Python



我很难在代码中插入排序

all_files = glob.glob(path + "/*.CSV") # To get all csv files disorganized
all_csv = [pd.read_csv(f, sep=',') for f in all_files] # List of dataframes
# I want to sort it by the values of the first column of each dataframe in the all_csv list.
for f in all_csv:
goal = pd.DataFrame.sort_values(by=(f.iloc[:,0])) #Maybe something like this??

所以,有人知道我该怎么做吗?我看过其他帖子,但不适用于未定义的列名(又名f.iloc[:,0](或数据帧列表(我也想过使用字典,但我想看看是否可以与列表一起使用(。

谢谢:(

可能有用的这个想法:链接,链接

这使用enke的代码按第一列对每个数据帧进行排序,但根据您的请求返回列表中的所有数据帧:

all_csv = [df.sort_values(by=df.columns[0]) for df in all_csv]

您可以为单个数据帧索引df.columns

goal = df.sort_values(by=df.columns[0])

对于整个数据帧列表,您可以使用列表理解:

all_csv = [df.sort_values(by=df.columns[0]) for df in all_csv]

假设您有一个数据帧,看起来像:

a  b
0  2  1
1  3  2
2  1  3

然后当你运行:

df = df.sort_values(by=df.columns[0])

df变为:

a  b
2  1  3
0  2  1
1  3  2

相关内容

  • 没有找到相关文章

最新更新