我有一個包含兩個串列的資料框,如何從串列中洗掉正數和負數?這是我的資料:https ://github.com/mayuripandey/Data-Analysis/blob/main/similarity.csv
輸入:[0,嗨。你好,好吧,-3]
預期輸出:[嗨,你好,好的]
uj5u.com熱心網友回復:
我會使用python的內置lstrip函式在開始時洗掉加號或減號,并使用該isnumeric方法檢查它是否為數字。
lst = ["0", "hi", "hello", "okay", "-3"]
is_num = lambda s : not s.lstrip(' -').isnumeric()
print(list(filter(is_num, lst))) # or [x for x in lst if is_num(x)]
# output : ['hi', 'hello', 'okay']
uj5u.com熱心網友回復:
一種方法是使用例外處理
def is_int(x):
try:
int(x)
except ValueError:
return False
else:
return True
input_ = [0, "hi", "hello", "okay", -3]
out = [i for i in input_ if not is_int(i)]
uj5u.com熱心網友回復:
看起來您正試圖從Model1_listandModel2_list列的開頭洗掉整數?如果是這種情況,您可能會發現 Python 的ast.literal_eval()函式很有用。這可以獲取這些列的字串并將它們轉換為 Python 串列。然后是選擇您想要的串列部分的簡單案例,例如使用 跳過第一個條目[1:]。
例如:
from ast import literal_eval
import csv
with open('similarity.csv') as f_input:
csv_input = csv.DictReader(f_input)
for row in csv_input:
model1_list = literal_eval(row['Model1_list'])[1:]
model2_list = literal_eval(row['Model2_list'])[1:]
print(f"{row['Name_1']:40} {str(model1_list):50} {model2_list}")
這會將兩個模型串列列轉換為 Python 串列并顯示它們:
-1_gun_dont_protect_like ['gun', 'dont', 'protect', 'like'] ['gun', 'peopl', 'right', 'get']
0_http_tco_freenrent_nhttp ['http', 'tco', 'freenrent', 'nhttp'] ['school', 'children', 'teacher', 'kid']
1_kavanaugh_brett_kill_near ['kavanaugh', 'brett', 'kill', 'near'] ['http', 'tco', 'freenrent', 'statehoodpr']
2_democrat_strategist_republican_care ['democrat', 'strategist', 'republican', 'care'] ['idiot', 'stupid', 'your', 'moron']
3_republican_democrat_gun_control ['republican', 'democrat', 'gun', 'control'] ['suprem', 'court', 'justic', 'assassin']
4_liber_leftist_left_riot ['liber', 'leftist', 'left', 'riot'] ['weapon', 'gun', 'assault', 'buy']
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/487935.html
標籤:Python 列表 数据框 CSV matplotlib
