使用条件设置已排序的多索引数据帧的第一行中的列值

2024-09-26 17:38:58 发布

您现在位置:Python中文网/ 问答频道 /正文

给定此示例:

df = pd.DataFrame(data=[(1, 'A', 5.0, 0.0),
                        (2, 'A', 3.0, 0.0),
                        (1, 'B', 1.0, 0.0),
                        (2, 'B', 2.0, 0.0),
                        (1, 'C', 6.0, 2.0)],
                  columns=('Date', 'Name', 'limit', 'allocation')).set_index(['Date','Name'])
groups = df.groupby('Date')
group = groups.get_group(1)
groupSorted = group.sort_values(by='limit', ascending=False)

现在groupSorted看起来是这样的:

           limit  allocation
Date Name                   
1    C       6.0         2.0
     A       5.0         0.0
     B       1.0         0.0

产生了groupSorted子数据帧之后,我想要一个公式set第一行的allocation满足allocation为0的条件。我该怎么做

我找到了各种方法来选择第一行。例如

groupSorted[groupSorted.allocation == 0].iloc[0]
groupSorted[groupSorted.allocation == 0].head(1)

。。。甚至是我想要改变的获取值的方法:

groupSorted[groupSorted.allocation == 0].iat[0, 1]
groupSorted[groupSorted.allocation == 0].iloc[0].at['allocation']
groupSorted[groupSorted.allocation == 0].iloc[0]['allocation']
groupSorted[groupSorted.allocation == 0]['allocation'].iat[0]

但是没有一个允许我设置这个值如何设置该值以使其“固定”在原始groupdf


Tags: 方法name示例dataframedfdategrouppd
1条回答
网友
1楼 · 发布于 2024-09-26 17:38:58

从评论到问题:

要分配给groupSorted,我们可以使用:

groupSorted.loc[(groupSorted['allocation'] == 0).idxmax(), 'allocation'] = 123

要将赋值“粘贴”到原始数据帧中,我们可以执行以下操作:

df.at[(groupSorted['allocation'] == 0).idxmax()] = 123

相关问题 更多 >

    热门问题