【问题标题】:Concatenate two data-frames and save unique value as txt连接两个数据框并将唯一值保存为 txt
【发布时间】:2021-06-26 02:56:59
【问题描述】:

这是我第一次发帖寻求帮助。

我有 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”?

谢谢

【问题讨论】:

    标签: python pandas dataframe concatenation


    【解决方案1】:

    您是否尝试从两个数据框中提取唯一的距离和直径值并将它们保存到 .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)
    

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

    【讨论】:

    • 感谢您的回复@AlexK 我正在尝试将 split_groups1 和 split_groups2 中的值保存到 txt 文件中。与父目录文件夹称为“解压”。我认为我需要一个按升序排列的列表,而不是一个数组。
    • @Kamz 哪些价值观?距离和直径的值(就像我展示的那样)或其他什么?数组和列表完成同样的事情。在我的回答中,结果是按升序打印的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-15
    • 1970-01-01
    • 2020-06-07
    • 2012-03-25
    • 1970-01-01
    • 2011-02-21
    • 2014-03-23
    相关资源
    最近更新 更多