首页 > 解决方案 > 连接两个数据框并将唯一值保存为 txt

问题描述

这是我的第一篇文章,我正在寻求帮助。

我有 2 个共享一些唯一值的大型 csv 文件,我编写了一个小型 python 脚本来帮助提取唯一字段并将它们保存到子目录中。我遇到的问题是我想将提取的值作为提取的.txt 文件保存到父文件夹。

import numpy as np 
import pandas as pd
import os
import json


large = pd.read_csv('large.csv')
medium = pd.read_csv('medium.csv')

#Grouped and split our dataframes by 'Distance & Diameter'
split1_groups = large.groupby('Distance')
split2_groups = medium.groupby('Diameter')

#loop through the groups and save to directories based on unique values
for name, group in split1_groups:
  if not os.path.exists(name):
    os.mkdir(name)
  group.to_csv(name + "/large.csv", index=0)

for name, group in split2_groups:
  if not os.path.exists(name):
    os.mkdir(name)
  group.to_csv(name + "/medium.csv", index=0)

在我遍历组后,如何将提取的值保存到 .txt & 并将新的子目录文件夹名称设置为“extracted”?

谢谢

标签: pythonpandasdataframeconcatenation

解决方案


您是否尝试从两个数据框中提取唯一的距离和直径值并将它们保存到 .txt 文件中?

您可以使用以下方法从数据框中的列中获取唯一值.unique()

unique_dist_vls = large.Distance.unique()
unique_diam_vls = medium.Diameter.unique()

然后您可以使用它将每个数组保存到 .txt 文件中(每个唯一值将打印在文件中的单独行上):

import os
os.makedirs("extracted")

with open("./extracted/extracted.txt", "w") as txt_file:
   print("\n".join(unique_dist_vls), file=txt_file)

如果这不能完全解决您的问题,请说明您的预期输出是什么。


推荐阅读