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

编程入门 行业动态 更新时间:2024-10-22 17:32:42
本文介绍了强制 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) 解释为字符串而不是范围?

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

发布评论

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

>www.elefans.com

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