[英]How to filter my CSV results using Python
I have a csv file where i have columns as follows:我有一个 csv 文件,其中的列如下:
Source Rack Switch Label/ID Switch no Switch Port
1 Hostname1 Switch1 1
with around 100 values in them.其中大约有 100 个值。 My goal is to filter the Label and see how many ports are used.
我的目标是过滤标签并查看使用了多少端口。 Apart from that, get a count value of the number of ports used by the switch.
除此之外,获取交换机使用的端口数的计数值。
Using CSVreader i get the values in python but i am stuck trying to filter them.使用 CSVreader 我在 python 中获取值,但我在尝试过滤它们时被卡住了。 Please suggest a method to get this done.
请提出一种方法来完成这项工作。
Thanks!谢谢!
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())
If I've understood correctly, you want something like this:如果我理解正确,你想要这样的东西:
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
Which results in:结果是:
label switch_no switch_port
0 hostname1 Switch1 1
1 hostname1 Switch1 1
2 hostname2 Switch1 2
3 hostname2 Switch2 3
After:后:
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.