强制 pandas 将列中的(1,2)解释为字符串而不是范围?

编程入门 行业动态 更新时间:2024-10-23 02:05:54
本文介绍了强制 pandas 将列中的(1,2)解释为字符串而不是范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在pandas Dataframe中有这种奇怪的行为.我在具有以下示例内容的列上使用.apply(single_seats_comma):(1,2).但是,它似乎以range(1,3)而不是字符串(1,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)解释为字符串而不是范围?

本文发布于:2023-06-08 21:27:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/589352.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   而不是   pandas   将列中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!