如何在 Python 中反轉布林陣列的元素?
有時,任務是反轉布林陣列。如果檔案包含一列具有真或假值的列,並且需要以反轉的方式使用列值,則通常需要這樣做。例如,如果 CSV 檔案包含資料列作為 Covid 陰性狀態,對 Covid 陰性患者顯示 True,並且需要建立 Covid 陽性狀態的列。在這種情況下,需要對布林值進行陣列反轉。在這篇 Python 文章中,使用四個不同的示例,給出了在使用或不使用 numpy 的情況下反轉布林陣列的不同方法。此外,本文還顯示了表示原始陣列和反轉陣列中布林值的圖形。
用於獲取布林列資料的 data.csv 檔案
Patientname,covidnegative Raju,True Meena,False Happy,True ……,……
示例 1:使用 Numpy 反轉布林陣列並比較布林值圖
演算法
步驟 1 − 首先匯入 pandas、numpy 和 plotly。Plotly 是 Python 的開源繪相簿,將用於製作散點圖。
步驟 2 − 現在讀取 data.csv 檔案,將其轉換為資料幀,並製作一個散點圖,在 Y 軸上顯示布林列“covidnegative”。
步驟 3 − 讀取布林列值。現在使用 numpy 函式將其轉換為陣列,然後使用 numpy 的 invert 函式反轉陣列。
步驟 4 − 在資料幀中新增一個新的列“covidpositive”並新增反轉的值。
步驟 5 − 再次製作一個散點圖,在 Y 軸上顯示布林列“covidpositive”。
步驟 6 − 編寫函式以顯示散點圖。使用 cmd 視窗執行程式。圖表將在瀏覽器的新選項卡中開啟。比較兩個圖表的 y 軸。
#include the required libraries
import pandas as pd
import numpy as np
#This library is needed to make the scatter plot
import plotly.express as pxx
#read the csv file and make a dataframe
dff = pd.read_csv("data.csv")
#print the colums and data
#make the scatter plot
figg = pxx.scatter(dff, x="patientname", y="covidnegative")
#set the properties of the scatter plot
figg.update_traces(marker=dict(size=12, line=dict(width=2, color="blue")), selector=dict(mode='markers'))
#display the chart
figg.show()
covidstatus=dff["covidnegative"]
arr = covidstatus.to_numpy()
#print(arr)
arr_inver = np.invert(arr)
#print(arr_inver)
dff['covidpositive'] = arr_inver.tolist()
#print(dff)
#make the scatter plot
figg = pxx.scatter(dff, x="patientname", y="covidpositive")
#set the properties of the scatter plot
figg.update_traces(marker=dict(size=12, line=dict(width=2, color="red")), selector=dict(mode='markers'))
#display the chart
figg.show()
輸出
在命令視窗中執行 Python 檔案 −

下圖顯示了原始和反轉陣列中布林值的圖。


示例 2:使用 ~ 對 Numpy 的陣列反轉布林值陣列
演算法
步驟 1 − 首先匯入 pandas 和 numpy。
步驟 2 − 現在讀取 data.csv 檔案,將其轉換為資料幀,並列印資料幀。
步驟 3 − 讀取布林列值。現在使用 numpy 函式將其轉換為陣列,然後使用 numpy 陣列上的 ~ 反轉陣列。
步驟 4 − 在資料幀中新增一個新的列“covidpositive”並新增反轉的值。再次列印資料幀。
步驟 5 − 使用 cmd 視窗執行程式。比較原始和反轉值的布林列。
#include the required libraries
import pandas as pd
import numpy as npp
#read the csv file and make a dataframe
dff = pd.read_csv("data.csv")
print("\nDataframe showing Boolean Value Column in CSV file")
print(dff)
covidstatus=dff["covidnegative"]
arr01 = covidstatus.to_numpy()
print("\nBoolean Column of CSV as array: ")
print(arr01)
inverted_arr01 = ~npp.array(arr01, dtype=bool)
print("\nBoolean Column of CSV as inverted array : ")
print(inverted_arr01)
dff['covidpositive'] = inverted_arr01.tolist()
print("\nNew dataframe with inverted column added :")
print(dff)
輸出
在命令視窗中執行 Python 檔案 −

示例 3:使用 Numpy 的 Logical_not 反轉布林值陣列
演算法
步驟 1 − 首先匯入 pandas 和 numpy。
步驟 2 − 現在讀取 data.csv 檔案,並將其轉換為資料幀。
步驟 3 − 讀取布林列值。現在使用 numpy 函式將其轉換為陣列並列印它。現在使用 NumPy 陣列上的 logical_not 反轉陣列並再次列印它。
步驟 4 − 在資料幀中新增一個新的列“covidpositive”並新增反轉的值。
步驟 5 − 使用 cmd 視窗執行程式。比較兩個陣列中原始值和反轉值。
#include the required libraries
import pandas as pd
import numpy as npp
#read the csv file and make a dataframe
dff = pd.read_csv("data.csv")
covidstatus=dff["covidnegative"]
arr01 = covidstatus.to_numpy()
print("\nA given boolean array: ", arr01)
arr_inver = npp.logical_not(arr01)
print("\nThe inverted boolean array: ", arr_inver)
dff['covidpositive'] = arr_inver.tolist()
#print(dff)
輸出
在命令視窗中執行 Python 檔案 −

示例 4:不使用 Numpy 反轉布林值陣列
演算法
步驟 1 − 匯入 CSV,然後使用 csv.DictReader 讀取包含布林值列的 CSV 檔案。
步驟 2 − 建立單獨的空陣列以儲存來自 CSV 檔案列的值,並將列值追加到這些陣列。
步驟 3 − 定義一個函式“reverse_bool”將 true 轉換為 false,將 false 轉換為 true 並返回反轉的值。
步驟 4 − 使用 map 函式使用“reverse_bool”函式將每個 false 轉換為 true,將 true 轉換為 false。
步驟 5 − 使用 cmd 視窗執行程式。比較兩個陣列中原始值和反轉值。
invertbool3.py
# importing the module
import csv
# open the file in read mode
filename01 = open('data.csv', 'r')
# creating dictreader object
file01 = csv.DictReader(filename01)
# creating empty lists
covidstatus = []
name=[]
def reverse_bool(status):
if status == "True":
return "False"
elif status == "False":
return "True"
print('\nMaking the arrays from the columns of data.csv file')
# iterating over each row and append
# values to empty list
for col in file01:
covidstatus.append(col['covidnegative'])
name.append(col['patientname'])
# printing lists
print('\nThe patient name:',name)
print('\nCovid -ve Status:', covidstatus)
print('\nReversing the boolean arrays made from the columns of data.csv file')
resultbool = list(map(reverse_bool, covidstatus))
print('\nCovid -ve Status:', covidstatus)
print('\nCovid +ve Status:', resultbool)
輸出
在命令視窗中執行 python 檔案 −

在這篇 Python 文章中,透過四個不同的示例,給出瞭如何反轉布林陣列的方法。前三種方法使用 NumPy 的函式來反轉布林值。然後編寫一個 Python 程式來建立反轉陣列而不使用 numpy。在第一個示例中,還比較了散點圖,以顯示布林原始值以及反轉值。
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP