python - 使用 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 []
解决方案
罪魁祸首是sum(df2['col3_y'])
。sum
需要一个数字列表,并且您有一个列表列表。
>>> sum([1,2])
3
>>> sum([[],[]])
TypeError: unsupported operand type(s) for +: 'int' and 'list'
推荐阅读
- macos - /bin/zsh 在 launchd 运行时无法打开脚本
- ruby-on-rails - = javascript_include_tag "application" 给出错误 ExecJS::RuntimeError at / SyntaxError: [stdin]:1:1: unexpected //=
- javascript - 当我调用 array.length 时,数组长度不正确
- python - iterrows(), itertuples() 使用不同的行值迭代 pandas 数据帧
- reactjs - React.memo 根本没有运行
- java - 如何添加 2 个标记,每个标记都有自己的信息窗口
- python - 我在 pip install src python3.6 上有错误
- permissions - Google Play 商店拒绝我的错误版本更新
- node.js - 将 Node\Express 应用程序部署到生产环境——它只是在复制吗?
- javascript - 循环遍历一个数组以填充另一个数组。(或对象?)