![](/img/trans.png)
[英]Trying to take info from a CSV file, rearrange the columns and then write the new output to a new CSV file in Python
[英]Python csv file - Open a csv file and take all info from 2 columns, get unique values and then remove some replies(without Pandas)
我創建了一個包含 5 列的 csv 文件
Machines | VM | Status | Node | Resolve
我想獲取節點和解析下的所有值,找到唯一值,然后刪除某些響應(那里有一些我不需要的“無”和“記錄”)。
做這個的最好方式是什么?
我試圖一次取 1 列,然后將其放入確實有效的集合中,但有更快的方法嗎? 然后我試圖從集合中拿走我不需要的值,但意識到我最終得到的一些值最后有 \n 。
通常我使用我喜歡的 Pandas,但我目前無法在我正在使用的機器上使用它。
unique3=[]
with open("machines.csv", "r") as file:
mach = file.readlines()
for c in mach:
split_lines = c.split(",")[3]
unique3.append(split_lines)
unique4=[]
with open("machines.csv", "r") as file2:
mach2 = file2.readlines()
for c in mach2:
split_lines2 = c.split(",")[4]
unique4.append(split_lines2)
uniqueunique = (set(unique4 + unique3))
非常感謝任何幫助,我知道這可能是直截了當的,但我在列表和字符串方面遇到了困難
像這樣的東西:
import csv
with open("machines.csv", "r") as f:
rdr = csv.reader(f)
next(rdr) # skip header if any, otherwise - remove this line
*_, node, resolve = zip(*rdr)
unique = set(node).union(set(resolve))
print(unique)
然后您可以刪除不需要的值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.