强制 pandas 将列中的 (1,2) 解释为字符串而不是范围? [英] Force pandas to interpret (1,2) in column as string and not as range?

查看:22
本文介绍了强制 pandas 将列中的 (1,2) 解释为字符串而不是范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在熊猫数据框中有这种奇怪的行为.我在具有以下示例内容的列上使用 .apply(single_seats_comma):(1,2).但是,它似乎将其返​​回为 range(1,3) 而不是字符串 (1,2).其他行也有超过 2 个条目,例如(30,31,32).我有一个函数,它在 , 上拆分并将括号中的每个值转换为一个新行,但是 (x,x) 它会中断.

I have this weird behaviour in a pandas Dataframe. I am using .apply(single_seats_comma) on a column with the following example content: (1,2). However, it seems to return it as range(1,3) instead of a string (1,2). Other rows have more than 2 entries as well, e.g. (30,31,32). I have a function which splits on , and converts each value in brackets into a new row however with (x,x) it breaks.

def single_seats_comma(row):
    strlist = str(row).split(',')
    strlist = filter(None, strlist) 
    intlist = []
    for el in strlist:
        intlist.append(int(el))
    return intlist

申请"示例:

tickets['seats'][:1].apply(single_seats_comma)

def 的错误输出是

ValueError: invalid literal for int() with base 10: 'range(1'

试图找到解决方案,我发现了这个:

Trying to find a solution, I found this:

str(tickets['seats'][:1])
>>'0    (1, 2)\nName: seats, dtype: object'

tickets['seats'][:1].values
>> '[range(1, 3)]'

如果值只是 1,2,它适用于列.

It works on a column if the values are just 1,2.

非常感谢任何帮助!

推荐答案

感谢所有贡献者让我更接近解决方案.解决方法其实很简单.

Thanks to all contributors to get me closer to a solution. The solution is actually quite simple.

挑战在于熊猫将 (1,2) 解释为范围而不是字符串.然而,目标是创建一个包含所有值的列表,最初是通过在 ',' 上拆分字符串.不需要!

The challenge was that pandas interpreted (1,2) as range and not as string However, the target was to create a list of all values, originally by splitting a string on ','. Not needed!

list(range(1,2)) 已经完成了这项工作.这是示例和解决方案:

list(range(1,2)) does the job already. Here is the example and solution:

list(range(11, 17))
>> [11, 12, 13, 14, 15, 16]

tickets['seats'][0]
>> range(1, 3)

list(alltickets['seats'][0])
>> [1, 2]

所以解决方案:

def single_seats_comma(row):
    strlist = list(row)
    return strlist

tickets['seats'].apply(single_seats_comma)

tickets['seats'].apply(lambda row: list(row))

这篇关于强制 pandas 将列中的 (1,2) 解释为字符串而不是范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆