我正在对Pandas应用一个函数DataFrame
,并返回一个tuple
,以DataFrame
使用转换成多列zip(* )
。
返回的tuple
包含一个list
,其中包含一个或多个tuples
。
如果嵌套的至少一个lists
包含tuples
与其余嵌套不同的计数lists
,则一切正常。
在极少数情况下,函数返回所有嵌套的lists
具有相等 tuple
计数的嵌套,AssertionError: Shape of new values must be compatible with manager shape
会引发an 。
我怀疑Pandas看到了一致的嵌套list
长度,并试图将它们拆list(tuples)
成单独的列。
list
无论上述条件如何,我如何强制熊猫始终按原样存储返回的商品?
(Python 3.7.4,Pandas 1.0.3)
起作用的代码:
import pandas as pd
import numpy as np
def simple_function(type_count):
calculated_value1 = np.random.randint(5)
calculated_value2 = np.random.randint(5)
types_list = [tuple((x, calculated_value2)) for x in range(0, type_count)]
return calculated_value1, types_list
df = pd.DataFrame([{'name': 'Joe', 'types': 1},
{'name': 'Beth', 'types': 1},
{'name': 'John', 'types': 1},
{'name': 'Jill', 'types': 2},
], columns=['name', 'types'])
df['calculated_result'], df['types_list'] = zip(*df['types'].apply(simple_function))
引发的代码AssertionError: Shape of new values must be compatible with manager shape
:
import pandas as pd
import numpy as np
def simple_function(type_count):
calculated_value1 = np.random.randint(5)
calculated_value2 = np.random.randint(5)
types_list = [tuple((x, calculated_value2)) for x in range(0, type_count)]
return calculated_value1, types_list
df = pd.DataFrame([{'name': 'Joe', 'types': 1},
{'name': 'Beth', 'types': 1},
{'name': 'John', 'types': 1},
{'name': 'Jill', 'types': 1},
], columns=['name', 'types'])
df['calculated_result'], df['types_list'] = zip(*df['types'].apply(simple_function))
通过在结果列表中创建一个DataFrame:
df[['calculated_result','types_list']] = pd.DataFrame(df['types'].apply(simple_function).tolist())
您可以使用数组获得类似的结果
df['calculated_result'], df['types_list'] = np.array(df['types'].apply(simple_function).tolist()).T
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句