我在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)解释为字符串而不是范围?
发布评论