英文:
Find matches between a list and dataframe column
问题
我想要在pandas数据框中创建一个过滤器,并在数据框中打印特定值,比如如果所有项目都不可用,就打印"Failed"。
data.csv内容:
server,ip
server1,192.168.0.2
data,192.168.0.3
server3,192.168.0.100
server4,192.168.0.10
我创建了以下代码:
import pandas as pd
l = ['server1','server2']
ip_list = ['192.168.0.2','192.168.0.100','192.168.25.4']
data = pd.read_csv('data.csv')
data_filter = data[
(data['ip'].isin(ip_list))
]
print(data_filter)
上述代码的输出如下:
server ip
0 server1 192.168.0.2
2 server3 192.168.0.100
我需要帮助以如下方式打印结果:
server ip Status
0 server1 192.168.0.2 Success
2 server3 192.168.0.100 Success
3 NA 192.168.25.4 Failed
请指导我如何创建这段代码?
英文:
I want to create a filter in pandas dataframe and print specific values like failed if all items are not available in dataframe.
data.csv content:
server,ip
server1,192.168.0.2
data,192.168.0.3
server3,192.168.0.100
server4,192.168.0.10
I created below code:
import pandas as pd
l = ['server1','server2']
ip_list = ['192.168.0.2','192.168.0.100','192.168.25.4']
data = pd.read_csv('data.csv')
#count = ip_list.count()
data_filter = data[
(data['ip'].isin(ip_list) )
]
print(data_filter)
Above code is printing result as below:
server ip
0 server1 192.168.0.2
2 server3 192.168.0.100
I need help to print result as below
server ip Status
0 server1 192.168.0.2 Success
2 server3 192.168.0.100 Success
3 NA 192.168.25.4 Failed
Please guide me how can I create this code?
答案1
得分: 0
使用pandas.DataFrame.merge
和pandas.Series.map
函数:
df_filtered = (df.merge(pd.DataFrame(ip_list, columns=['ip']),
on='ip', how='right', indicator='Status'))
df_filtered['Status'] = df_filtered['Status'].map({'both': 'Success', 'right_only': 'Failed'})
结果如下:
server ip Status
0 server1 192.168.0.2 Success
1 server3 192.168.0.100 Success
2 NaN 192.168.25.4 Failed
英文:
With pandas.DataFrame.merge
+ pandas.Series.map
functions:
df_filtered = (df.merge(pd.DataFrame(ip_list, columns=['ip']),
on='ip', how='right', indicator='Status'))
df_filtered['Status'] = df_filtered['Status'].map({'both': 'Success', 'right_only': 'Failed'})
server ip Status
0 server1 192.168.0.2 Success
1 server3 192.168.0.100 Success
2 NaN 192.168.25.4 Failed
答案2
得分: 0
This should do the trick:
import pandas as pd
l = ['server1', 'server2']
ip_list = ['192.168.0.2', '192.168.0.100', '192.168.25.4']
data = pd.read_csv('data.csv')
#count = ip_list.count()
data['Status'] = list(map(lambda x: 'Success' if x else 'Failed', data['ip'].isin(ip_list)))
print(data)
英文:
This should do the trick:
import pandas as pd
l = ['server1','server2']
ip_list = ['192.168.0.2','192.168.0.100','192.168.25.4']
data = pd.read_csv('data.csv')
#count = ip_list.count()
data['Status'] = list(map(lambda x: 'Success' if x else 'Failed', data['ip'].isin(ip_list)))
print(data)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论