我有一个大熊猫系列,其中每个细胞都是一个元组.我正在尝试对该系列执行rolling().apply(),而我正在尝试应用的函数永远不会被调用.这是一个愚蠢的例子,显示了我在说什么:
>>> import pandas as pd
>>> pd.__version__
u'0.18.0'
>>> die = lambda x: 0/0
>>> s = pd.Series(zip(range(5), range(5)))
>>> s
0 (0, 0)
1 (1, 1)
2 (2, 2)
3 (3, 3)
4 (4, 4)
dtype: object
Run Code Online (Sandbox Code Playgroud)
一个简单的apply工作正如预期的那样,函数被调用:
>>> s.apply(die)
[...]
ZeroDivisionError: integer division or modulo by zero
Run Code Online (Sandbox Code Playgroud)
但是a rolling().apply()根本没有做任何事情,特别是应该应用的函数永远不会被调用:
>>> s.rolling(2).apply(die)
0 (0, 0)
1 (1, 1)
2 (2, 2)
3 (3, 3)
4 (4, 4)
dtype: object
Run Code Online (Sandbox Code Playgroud)
这是演示我正在谈论的最简单的例子,但是套件和列表也是如此.
为什么会发生这种情况,如何在一系列集合中使用自定义函数进行滚动应用?
为什么尝试创建curried函数列表不起作用?
def p(x, num):
print x, num
def test():
a = []
for i in range(10):
a.append(lambda x: p (i, x))
return a
>>> myList = test()
>>> test[0]('test')
9 test
>>> test[5]('test')
9 test
>>> test[9]('test')
9 test
Run Code Online (Sandbox Code Playgroud)
这里发生了什么?
实际上我希望上述函数执行的功能是:
import functools
def test2():
a = []
for i in range (10):
a.append(functools.partial(p, i))
return a
>>> a[0]('test')
0 test
>>> a[5]('test')
5 test
>>> a[9]('test')
9 test
Run Code Online (Sandbox Code Playgroud) 我很好奇周围的Python Ninjas如何优雅和诡异地执行以下操作:
我有一个数据结构,它是从unicode字符串到unicode字符串到unicode字符串列表的字典.所以:
>>> type(myDict)
<type 'dict'>
>>> type(myDict[u'myKey'])
<type 'dict'>
>>> type(myDict[u'myKey'][u'myKey2'])
<type 'list'>
>>> type(myDict[u'myKey'][u'myKey2'][0])
<type 'unicode'>
Run Code Online (Sandbox Code Playgroud)
我想通过并使每个字符串小写,即每个列表中的每个键和每个字符串.
你会怎么做?