python - 连接两个数据框并将唯一值保存为 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”?
谢谢
解决方案
您是否尝试从两个数据框中提取唯一的距离和直径值并将它们保存到 .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)
如果这不能完全解决您的问题,请说明您的预期输出是什么。
推荐阅读
- javascript - 训练营和代码沙盒挑战告诉我 axios 没有定义
- css - 如何模糊按钮的轮廓?
- swift - 支持 macOS 应用程序中的 URL 方案
- python - 如何使用python离线访问谷歌表格
- python - Convert `pandas` frequency string to `DateOffset`
- java - 获取spring kafka中未处理的消息计数
- python - 在 python 中编写迭代的问题
- reactjs - 头盔导致 Heroku 上托管的 MERN 应用程序导致错误:拒绝执行内联脚本,因为它违反了以下内容
- node.js - 尝试访问我的 firebase 数据库时出现分段错误(核心转储)
- pip - 错误:由于 OSError 无法安装软件包:[Errno 22]