在 Pandas DataFrame 组中设置值

时间:2021-02-12 20:53:00

标签: pandas dataframe pandas-groupby

如何在不触发 SettingWithCopyWarning 的情况下在 DataFrame 组中分配值?

我希望能够获得对 DataFrame 组的引用,然后能够访问和设置该组中的列值。

我不能使用 .apply.transform,因为我会在设置值时使用 need to reference the preceding group

所以,例如:

df = pd.DataFrame(data=[('A', '20210101', 9.0, False),
                        ('B', '20210101', 5.0, False),
                        ('C', '20210101', 5.0, True),
                        ('A', '20210102', 0.0, False),
                        ('B', '20210102', 0.0, False),
                        ('C', '20210102', 0.0, False)],
                  columns=('Name', 'Date', 'Dollars', 'HaveMax')).set_index(['Name', 'Date'])

假设我想设置 Dollars 的值在哪里 Date == '20210102?我发现:

df.groupby('Date').indices.get('20210102')  # << Gets array of the rows
df.iloc[df.groupby('Date').indices.get('20210102')]  # << Gets the rows

但是 df.iloc[df.groupby('Date').indices.get('20210101')]['Dollars'] = 3 给出了 SettingWithCopyWarning

我认为可以实现我的目标的是一个代码示例,它将 Dollars 上每个 Name 的 '20210102' 设置为,例如,将 Dollars 上每个 Name 的 '20210101' 加倍。< /p>

1 个答案:

答案 0 :(得分:1)

这应该对你有用

df.loc[df.index.get_level_values('Date') == '20210101', 'Dollars'] = 3

输出

df
               Dollars  HaveMax
Name Date
A    20210101    3.000    False
B    20210101    3.000    False
C    20210101    3.000     True
A    20210102    0.000    False
B    20210102    0.000    False
C    20210102    0.000    False

分配给上一个日期的值:

df.loc[df.index.get_level_values('Date') == '20210102', 'Dollars'] = df.iloc[df.groupby('Date').indices.get('20210101')].Dollars.values