python - 使用基于数据框中其他列的函数向 pandas 数据框添加值

标签 python pandas

这听起来与很多SO问题相似,但我实际上还没有找到它;如果在这里,请随时链接,我会删除。

我有两个数据框。第一个看起来像这样:

owned   category                            weight  mechanics_split
28156   Environmental, Medical              2.8023  [Action Point Allowance System, Co-operative P...
9269    Card Game, Civilization, Economic   4.3073  [Action Point Allowance System, Auction/Biddin...
36707   Modern Warfare, Political, Wargame  3.5293  [Area Control / Area Influence, Campaign / Bat...

第二个看起来像这样:

    type                            amount  owned
0   Action Point Allowance System   378     0
1   Co-operative Play               302     0
2   Hand Management                 1308    0
3   Point to Point Movement         278     0
4   Set Collection                  708     0
5   Trading                         142     0

我想做的是迭代mechanics_split中的每个单词,以便将第一个数据帧中的owned值添加到owned中第二个数据框中的 code> 列。例如,如果 Dice Rolling 位于 mechanics_split 列中 games 的第一行,则该整行的拥有金额将添加到 games_owned['owned' ] 等,对于整个数据帧中 mechanics_split 列表中的每个值。

到目前为止,我已经尝试过:

owned_dict = {}
def total_owned(x):
    for e in x:
        if e not in owned_dict:
            owned_dict[e] = 0
        if e in owned_dict:
            owned_dict[e] += games['owned'][x]
    return owned_dict

返回:

KeyError: "None of [['Action Point Allowance System', 'Co-operative Play', 'Hand Management', 'Point to Point Movement', 'Set Collection', 'Trading', 'Variable Player Powers']] are in the [index]"

如果我在 e 之前添加另一个字母,我会被告知需要解压的值太多。我还尝试跳过字典并仅使用 otherdf['owned'][e] += games['owned'][x] 无济于事。

我可能从根本上误解了索引在 pandas 中的工作原理以及如何将值索引到行,所以如果我是这样,请告诉我。非常感谢您的帮助。

编辑:我通过使用“otherdf.index = otherdf.types”将第二个数据帧的索引更改为“types”列解决了部分问题,但仍然存在传输数据的问题来自第一个数据帧的拥有值。

最佳答案

我同意你的观点,使用“类型”列作为基于标签的索引会让事情变得更容易。完成此操作后,您可以迭代第一个数据帧的行,然后使用 . loc method .

for row_1 in df_1.itterrows():
  owned_value = row_1[1]['owned'] #iterrows() enumeration generator over rows      
  mechanics =  row_1[1]['mechanics_split']
  for type_string in mechanics:
    df_2.loc[type_string,('owned')] += owned_value

此外,我建议阅读 how Pandas handles indexing帮助您在继续使用 Python 时避免任何“陷阱”。

关于python - 使用基于数据框中其他列的函数向 pandas 数据框添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44092423/

相关文章:

python - 合并多个数据帧并对值求和

python - Pandas 使用 apply 函数更新多列

Python 二进制搜索(最大迭代次数)

python - 排序的键值 lambda 不起作用

python - 是否有一种类似于使用上下文管理器在后台运行异步任务的 Pythonic 方式?

python - pycairo "ImportError: DLL load failed: The specified module could not be found."即使在安装 DLL 之后

python - 如何将一列乘以另一列乘以该月第一天的值

python - 将包含类别的列与包含整数的列合并

python - 按列对 csv 进行排序时出错

pandas - 如何更改散点图色调图例 handle