gpt4 book ai didi

python - 在 python 数据框中划分几列,其中分子和分母列将根据选择列表而变化

转载 作者:太空宇宙 更新时间:2023-11-04 00:37:01 26 4
gpt4 key购买 nike

我正在创建一个数据框,方法是根据最终用户在选择列表中所做的选择来配对一个非常大的数据框(大约 400 列)。选择列表的选择之一是最终用户想要的分母类型。这是一个示例表,其中包含进行最终计算之前的所有信息。

                county  _tcount  _tvote  _f_npb_18_count  _f_npb_18_vote  
countycode
35 San Benito 28194 22335 2677 1741
36 San Bernardino 912653 661838 108724 61832



countycode _f_npb_30_count _f_npb_30_vote
35 384 288
36 76749 53013

但是,我无法创建自动将从第 5 列开始的每一列(不包括索引)除以它之前的列(跳过所有其他列)的代码。我看过示例 ( Divide multiple columns by another column in pandas ),但它们都使用固定的列名,这在这方面是无法实现的。我能够通过固定列改变列(基于位置),但不能通过基于位置的其他可变列改变列。我尝试根据列位置修改上述链接中的代码:

calculated_frame = [county_select_frame[county_select_frame.columns[5: : 2]].div(county_select_frame[4: :2], axis=0)]

输出:

[           county  _tcount  _tvote  _f_npb_18_count  _f_npb_18_vote  \
countycode
35 NaN NaN NaN NaN NaN
36 NaN NaN NaN NaN NaN]

RuntimeWarning: invalid value encountered in greater (abs_vals > 0)).any()

[5::2] 的使用在股息是固定字段时确实有效。如果我不能让它工作,那没什么大不了的(但它会很棒拥有我想要的所有选项)。

最佳答案

我的偏好是通过设置索引并使用 filter 分别拆分计数和投票数据帧来组织它。然后使用加入

d1 = df.set_index('county', append=True)
counts = d1.filter(regex='.*_\d+_count$').rename(columns=lambda x: x.replace('_count', ''))
votes = d1.filter(regex='.*_\d+_vote$').rename(columns=lambda x: x.replace('_vote', ''))

d1[['_tcount', '_tvote']].join(votes / counts)

_tcount _tvote _f_npb_18 _f_npb_30
countycode county
35 San Benito 28194 22335 0.650355 0.750000
36 San Bernardino 912653 661838 0.568706 0.690732

关于python - 在 python 数据框中划分几列,其中分子和分母列将根据选择列表而变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43580566/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com