[英]How to filter my CSV results using Python
我有一個 csv 文件,其中的列如下:
Source Rack Switch Label/ID Switch no Switch Port
1 Hostname1 Switch1 1
其中大約有 100 個值。 我的目標是過濾標簽並查看使用了多少端口。 除此之外,獲取交換機使用的端口數的計數值。
使用 CSVreader 我在 python 中獲取值,但我在嘗試過濾它們時被卡住了。 請提出一種方法來完成這項工作。
謝謝!
import pandas as pd
import csv
import numpy
import matplotlib
#import datetime
#import pandas.io.data
data_df = pd.read_csv('patchingwlan.csv',index_col = 1)
data_df.filter(items=['Hostname','Switch Port'])
print(data_df.head())
如果我理解正確,你想要這樣的東西:
import pandas as pd
pd.set_option("display.width", 300)
# Test input data
df = pd.DataFrame({
"label": ["hostname1", "hostname1", "hostname2", "hostname2"],
"switch_no": ["Switch1", "Switch1", "Switch1", "Switch2"],
"switch_port": [1, 1, 2, 3]
})
print df
# Count ports per label and ports per switch_no (unique and total, depending on what you want)
df["unique_ports_per_label"] = df.groupby("label")["switch_port"].transform("nunique")
df["ports_per_label"] = df.groupby("label")["switch_port"].transform(len)
df["unique_ports_per_switch"] = df.groupby("switch_no")["switch_port"].transform("nunique")
df["ports_per_switch"] = df.groupby("switch_no")["switch_port"].transform(len)
print df
結果是:
label switch_no switch_port
0 hostname1 Switch1 1
1 hostname1 Switch1 1
2 hostname2 Switch1 2
3 hostname2 Switch2 3
后:
label switch_no switch_port unique_ports_per_label ports_per_label unique_ports_per_switch ports_per_switch
0 hostname1 Switch1 1 1 2 2 3
1 hostname1 Switch1 1 1 2 2 3
2 hostname2 Switch1 2 2 2 2 3
3 hostname2 Switch2 3 2 2 1 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.