繁体   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