簡體   English   中英

提取整數並將其存儲為元組列表中的新變量

[英]Extract integers and store them as new variable from a list of tuple

在數據框列中,我有一個包含int,str,float的元組列表。 我的目標是提取數值並將其存儲在新列中。 如果元組列表中有兩個數值,則應為兩個提取的值創建兩個變量。

輸入數據 -

List_Tuple 
[('watch','price','is','$','100')]
[('there', 'was', '2','apple','and','2','mango')]
[('2','cat'),('3','mouse')] 

我不確定是否可以做到,無法考慮下一步。 請指導和建議。

預期產出-

Var1 Var2
100  
2    2
2    3
final = []
for tup in my_tuple:
    for item in tup:
        if item.isdigit():
            final.append(item)

或作為列表理解:

[item for item in tup for tup in my_list if item.isdigit()]

如果您還想檢查浮點數,請使用isinstance(item, (int, float))例如:

[item for item in tup for tup in my_list if isinstance(item, (int, float))]

編輯:我相信這會為您提供所需的功能?

df = pd.DataFrame([[[('watch','price','is','$','100')]],
                  [[('there', 'was', '2','apple','and','2','mango')]],
                  [[('2','cat'),('3','mouse')]]])

df.columns = ['x1']

def tuple_join(row):
    tup = row[0]
    tup_int = [item for item in tup if item.isdigit()] 
    return (tup_int) 

test = lambda x: tuple_join(x) 
df['a1'] = pd.DataFrame(df.x1.apply(test))

讓我們使用以下測試數據:

List_Tuple = [
    [('watch','price','is','$','100')],
    [('there', 'were', '2','apples','and','2','mangos')],
    [('2','cats'),('3','mice')],
]

請注意,您的某些列表包含一個元組,而另一些包含兩個元組。 為了搜索數字值,將有助於將它們合並在一起。 來自`itertools'庫的chain.from_iterable可用於此目的:

考慮以下代碼:

for row in List_Tuple: 
    print(*itts.chain.from_iterable(row))

上面的代碼打印如下:

watch price is $ 100
there were 2 apples and 2 mangos
2 cats 3 mice

剩下的就是提取數字

import string
import re # regular expressions
def extract_numbers(in_data):
    out_data = list()
    for row in in_data:
        merged_row = itts.chain.from_iterable(row)
        merged_row = ''.join(merged_row)
        print(merged_row)
        match = re.search("\D*(\d+)\D*(\d*)", merged_row)
        groups = match.groups() if match != None else None
        out_data.append(groups)
    return out_data

print('\n'.join((str(x) for x in extract_numbers(List_Tuple))))

最后的打印語句顯示:

('100', '')
('2', '2')
('2', '3')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM