import pandas as pd df=pd.read_csv('H:/analysis_results/root_global_results_HN.csv') group_data=df.groupby(df['folder'].str[:-2]) #计算品种的平均值和标准差 #folder=df['folder'].str.split('').str[0] #mean=group_data.mean() #std=group_data.std() #print('mean:',round(mean,3)) #print('std:',round(std,3)) result=group_data.agg({'volume':['mean','std'], 'convex_volume':['mean','std'], 'surface_area':['mean','std'], 'length':['mean','std'], 'max_width':['mean','std'], 'max_depth':['mean','std']} ) #df = result.reset_index(inplace=True) # 将索引列转换为普通列result.reset_index(inplace=True) #result.columns = [''.join(col).strip() for col in result.columns.values] result.columns = result.columns.map(lambda x: f'{x[0]}_{x[1]}') result.index.name='folder' result.reset_index(inplace=True) #result = result.sort_values(by='folder') #result = result.sort_index() result = result[['folder', 'volume_mean', 'volume_std', 'convex_volume_mean', 'convex_volume_std', 'surface_area_mean', 'surface_area_std', 'length_mean', 'length_std', 'max_width_mean', 'max_width_std', 'max_depth_mean', 'max_depth_std']] result_path='H:/analysis_results/mean_std_HN.csv' result.to_csv(result_path,index=False) print('结果已保存到{}',format(result_path))如何根据csv文件中第一列folder字母后的数字进行排序
时间: 2023-08-22 12:09:03 浏览: 114
您可以使用Pandas的sort_values方法对DataFrame进行排序,代码示例如下:
```python
import pandas as pd
# 读取CSV文件
df = pd.read_csv('H:/analysis_results/root_global_results_HN.csv')
# 根据folder列进行排序,根据名称字母后的数字排序
df = df.sort_values(by=df['folder'].str.split('_').str[-1].astype(int))
# 对品种进行分组,计算平均值和标准差
group_data = df.groupby(df['folder'].str[:-2])
result = group_data.agg({
'volume': ['mean', 'std'],
'convex_volume': ['mean', 'std'],
'surface_area': ['mean', 'std'],
'length': ['mean', 'std'],
'max_width': ['mean', 'std'],
'max_depth': ['mean', 'std']
})
# 重置索引
result.reset_index(inplace=True)
result.columns = result.columns.map(lambda x: f'{x[0]}_{x[1]}')
result.index.name = 'folder'
# 重新排列列的顺序
result = result[['folder', 'volume_mean', 'volume_std', 'convex_volume_mean', 'convex_volume_std',
'surface_area_mean', 'surface_area_std', 'length_mean', 'length_std',
'max_width_mean', 'max_width_std', 'max_depth_mean', 'max_depth_std']]
# 保存结果到CSV
result_path = 'H:/analysis_results/mean_std_HN.csv'
result.to_csv(result_path, index=False)
print('结果已保存到{}'.format(result_path))
```
在这个示例中,我们使用Pandas的sort_values方法对DataFrame进行排序,根据CSV文件中第一列folder字母后的数字进行排序。然后,我们对品种进行分组,使用groupby方法计算平均值和标准差,最后将结果保存到CSV文件。
阅读全文