基于对reset_index

时间:2018-07-31 22:28:24

标签: python pandas

回答this question时,当我尝试基于对数据帧索引进行的基本计算来创建列时,遇到了我认为是意外的行为。 我并不是真的在寻找解决方案,而是试图找出原因的原因。我可能会忽略一些基本知识...

设置:

np.random.seed(42)

df = pd.DataFrame(np.random.randint(0,5,9), index=[0,1,2,0,1,2,0,1,2])

>>> df
   0
0  3
1  4
2  2
0  4
1  4
2  1
0  2
1  2
2  2

奇怪的行为:

比方说,我试图获取索引等于0的位置的累计和。我可以通过以下方式轻松获得该值:

>>> df.reset_index()['index'].eq(0).cumsum()
0    1
1    1
2    1
3    2
4    2
5    2
6    3
7    3
8    3
Name: index, dtype: int64

但是,如果我尝试将其直接分配给新列,则结果不正确:

df['new_column'] = df.reset_index()['index'].eq(0).cumsum()

>>> df
   0  new_column
0  3           1
1  4           1
2  2           1
0  4           1
1  4           1
2  1           1
0  2           1
1  2           1
2  2           1

如果我使用assign做同样的事情:

df.assign(new_column = df.reset_index()['index'].eq(0).cumsum())

预期的行为:

我希望结果看起来像这样:

>>> df
   0  new_column
0  3           1
1  4           1
2  2           1
3  4           2
4  4           2
5  1           2
6  2           3
7  2           3
8  2           3

解决方法:

有很多解决方法,例如:

df = df.reset_index().rename(columns={'index':'tmp'})

df['new_column'] = df.tmp.eq(0).cumsum()

df.drop('tmp', axis=1, inplace=True)

df.loc[0,'new_column'] = 1

df['new_column'] = df['new_column'].fillna(0).cumsum().astype(int)

问题:

但是,正如我所说的,我只对为什么在我直接从reset_index()分配新列时将新列设置为1

感谢您的输入!

2 个答案:

答案 0 :(得分:1)

仅是因为大熊猫将此匹配设置为索引。

您的系列是:

0    1
1    1
2    1
3    2
4    2
5    2
6    3
7    3
8    3

以上索引0、1和2的值均为1

一旦您的df仅将这些值用作索引,它将为所有行分配1。

答案 1 :(得分:1)

尽管是Data Frame的新手,我仍然可以使用

解决它
df['new_column'] = df.reset_index()['index'].eq(0).cumsum().values

我仍然必须弄清楚“为什么”。好的,如果没有.values,您将得到pandas.core.series.Series,而值将返回一个numpy数组,该数组可以直接分配给新列。