Filling pandas index-based data between two values

I am trying to create a mask for translation in dataframes: a boolean series that indicates whether a given string is between two values. This is easy to do for one logical operator, for example, the last five elements in a data frame:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.rand(10,1))
mask = (df.index.values>4)
df.loc[mask,'column'] = range(0,5)

But how to do the same thing with more cross-sectional statements? For example, instead of the last five components in an array, can I address lines 2 through 6? Trying to use the AND statement for the mask fails, and I cannot use Inter on the dataframe index value.

+4
source share
1 answer

, mask , .

, between, , to_series Series.

mask = df.index.to_series().between(2,6)
#mask = pd.Series(df.index, index=df.index).between(2,6)
print (mask)
0    False
1    False
2     True
3     True
4     True
5     True
6     True
7    False
8    False
9    False
dtype: bool

mask = df.index.to_series().between(2,6).values
print (mask)
[False False  True  True  True  True  True False False False]

&:

mask = (df.index >= 2) & (df.index <= 6)
print (mask)
[False False  True  True  True  True  True False False False]

, , loc, :

df.loc[2:6, 0] = range(5)
print (df)
          0
0  0.642933
1  0.912846
2  0.000000
3  1.000000
4  2.000000
5  3.000000
6  4.000000
7  0.504830
8  0.000422
9  0.029358
+2

Source: https://habr.com/ru/post/1680097/


All Articles