首页 > 解决方案 > 使用 numpy 进行条件向量化,如何将列表添加到数据框单元格

问题描述

我有两个数据框合并在一起,两个填充的整数列和第三列的空列表。

df = pd.DataFrame({'col1': ['z','x','c','v','b','n'], 'col2': [100, 200, 300, 400, 500, 600]})
df1 = pd.DataFrame({'col1': ['z','x','c','v','b','n'], 'col2': [10, 20, 300, 40, 50, 600]})   
df['col3'] = np.empty((len(df), 0)).tolist()
df1['col3'] = np.empty((len(df), 0)).tolist()

df2 = df.merge(df1, on='col1', how='outer')

这产生了这个

     col1  col2_x col3_x  col2_y col3_y
0    z      10     []      63     []
1    x      24     []    1365     []
2    c     642     []     356     []
3    v     462     []       2     []
4    b    2454     []     467     []
5    n      23     []      23     []

如果条件正确,我想进行一些计算,如果是,则在每个列表中添加一个值df2['col3_y']

condition = [
    ((df2['col2_y'] != df2['col2_x']) & (len(df2['col3_y']) < 1)),
    ((df2['col2_y'] != df2['col2_x']) & (len(df2['col3_y']) > 0))
]
action = [
    (df2['col2_y'] - df2['col2_x'])/1000,
    df2['col3_y'] + [(df2['col2_y'] - df2['col2_x'] - sum(df2['col3_y']))/1000]
]

df2['col3_y'] = np.select(condition, action)

但它给我一个错误TypeError: unsupported operand type(s) for +: 'int' and 'list' 显然意味着我已经转向错误的方向,如果有人可以纠正我并告诉我我做错了什么,我会很高兴,谢谢!

预期的

对于列表列中的每个单元格,if len(list) > 1在同一索引中df['col2_y']从其中减去值,df['col2_x']除以 1000,并将解决方案附加到列表中, elif len(list) > 0在同一索引中,df['col2_y']从其中df2['col2_x']减去值列表的总和df2['col3_y']除以 1000 并将解决方案附加到列表中。如果值df2['col2_x'] == df2['col2_y']什么都不做。

  col1  col2_x col3_x  col2_y    col3_y
0    z     100     []      10     [-0.09]
1    x     200     []      20     [-0.18]
2    c     300     []     300     []
3    v     400     []      40     [-0.36]
4    b     500     []      50     [-0.45]
5    n     600     []     600     []

标签: pythonpython-3.xpandasnumpyvectorization

解决方案


罪魁祸首是sum(df2['col3_y'])sum需要一个数字列表,并且您有一个列表列表。

>>> sum([1,2])
3
>>> sum([[],[]])
TypeError: unsupported operand type(s) for +: 'int' and 'list'

推荐阅读