cs9*_*s95 10 python apply dataframe pandas
考虑这个简单的数据帧:
a b
0 1 2
1 2 3
Run Code Online (Sandbox Code Playgroud)
我执行.apply
如下:
In [4]: df.apply(lambda x: [x.values])
Out[4]:
a [[140279910807944, 140279910807920]]
b [[140279910807944, 140279910807920]]
dtype: object
In [5]: df.apply(lambda x: [x.values])
Out[5]:
a [[37, 37]]
b [[37, 37]]
dtype: object
In [6]: df.apply(lambda x: [x.values])
Out[6]:
a [[11, 11]]
b [[11, 11]]
dtype: object
Run Code Online (Sandbox Code Playgroud)
为什么大熊猫每次都会打印出垃圾?
我已经在v0.20验证了这种情况.
编辑:寻找答案,而不是解决方法.
它看起来像bug,因此被打开了问题17487.
对我来说工作添加tolist
:
print (df.apply(lambda x: [x.values.tolist()]))
a [[1, 2]]
b [[2, 3]]
dtype: object
Run Code Online (Sandbox Code Playgroud)
print (df.apply(lambda x: [list(x.values)]))
a [[1, 2]]
b [[2, 3]]
dtype: object
Run Code Online (Sandbox Code Playgroud)
我没有答案......只是一个解决方法
f = lambda x: x.values.reshape(1, -1).tolist()
df.apply(f)
a [[1, 2]]
b [[2, 3]]
dtype: object
Run Code Online (Sandbox Code Playgroud)
我跟踪它 pd.lib.reduce
pd.lib.reduce(df.values, lambda x: [list(x)])
array([list([[1, 2]]), list([[2, 3]]), list([['a', 'b']])], dtype=object)
Run Code Online (Sandbox Code Playgroud)
与
pd.lib.reduce(df.values, lambda x: [x])
array([list([array([None, None], dtype=object)]),
list([array([None, None], dtype=object)]),
list([array([None, None], dtype=object)])], dtype=object)
Run Code Online (Sandbox Code Playgroud)