【发布时间】:2021-07-14 02:50:30
【问题描述】:
我需要一些帮助以升序将列中的值写入文本文件。
我当前的代码创建了一个名为values 的目录,并将从列中提取的值保存到 .txt 文件中,但它不是我想要的升序。
values_dir=os.path.join(cwd, 'values')
if not os.path.exists(values_dir):
os.mkdir(values_dir)
with open(os.path.join(values_dir, 'values.txt'), "w") as txt_file:
for name, group in split_location:
txt_file.write(str(name) + '\n')
代码将我的值保存为
data23
data17
data88
我希望它保存为
data17
data23
data88
如果有人能指出我正确的方向,将不胜感激,谢谢。
编辑
我通过字段 Data 和 Data_Unit 中的唯一值拆分了 2 个大型数据帧
datafile = pd.read_csv('location.csv')
datafile_large = pd.read_csv('large.csv')
split_location = datafile.groupby('Data')
split_large = datafile_large.groupby('Data_Unit')
然后,我遍历这些组并根据其唯一值将拆分的数据帧保存到子目录,同时保留父文件名。
for name, group in split_location:
sub_dir = os.path.join(cwd, name)
if not os.path.exists(sub_dir):
os.mkdir(sub_dir)
group = group.drop(['Data'], axis=1)
group.to_csv(sub_dir + "/location.csv", index=0)
for name, group in split_large:
sub_dir = os.path.join(cwd, name)
if not os.path.exists(sub_dir):
os.mkdir(sub_dir)
group = group.drop(['Data_Unit'], axis=1)
group.to_csv(sub_dir + "/large.csv", index=0)
最后我创建values.txt 文件,如开头所述。但是希望将.txt文件中保存的值按升序排列。
values_dir=os.path.join(cwd, 'values')
if not os.path.exists(values_dir):
os.mkdir(values_dir)
with open(os.path.join(values_dir, 'values.txt'), "w") as txt_file:
for name, group in split_location:
txt_file.write(str(name) + '\n')
【问题讨论】:
标签: python pandas sorting text