0

I have this data-frame:

index
name    a     b
1-1     1     2
1-2     2     4
5-1     3     6
5-2     4     8
7-1     5     4
7-2     6     5

I want to call only values starting with 'index name' = 5

index
name     a     b
5-1      3     6
5-2      4     8

I tried:

df = df.loc['index name'] == 5 

But I get SyntaxError: invalid token

Any advise on how to do it? thanks!

EDIT

If 'index name' is a column, It works with:

df = df.loc[df['your column'] == 5]

However, if 'index name' is an index, it does not work.

EDIT 2

If 'index name' is index, it works with:

df.loc[df.index.str.startswith('5')]
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Jack_T
  • 91
  • 1
  • 9

1 Answers1

2
df.loc[df["index name"].str.startswith("5")]

    index name  a   b
2   5-1         3   6
3   5-2         4   8
help-ukraine-now
  • 3,850
  • 4
  • 19
  • 36
  • Thanks, this one < df = df.loc[df['your column'] == 5] > worked if 'index name' is a column. However it does not work if 'index name' is an index. – Jack_T Jul 26 '20 at 10:36
  • with < df.loc[df["index name"].str.startswith("5")] > I still get < KeyError: index name > – Jack_T Jul 26 '20 at 10:38
  • 1
    @Jack_T if your column is an index, try: `df.loc[df.index.str.startswith("5")]` – help-ukraine-now Jul 26 '20 at 10:40
  • Thanks it worked! but there is another issue when changing 'index_name'. Please have a look at edit 2, thanks! – Jack_T Jul 26 '20 at 10:47
  • @Jack_T, that's strange. Are you sure you didn't overwrite your original df with a copy where index starts with 5? because if no index starts with 1 or 7, there's nothing to return. – help-ukraine-now Jul 26 '20 at 10:51
  • scentist one quick question: if I want to call 'index name' 5 and 7 together, I have tried < df.loc[df.index.str.startswith("5", "7")] > and also < .....startswith(["5", "7"]) > but I get an error < key erorr: "None of [Float64Index([nan, nan, nan, nan.. ] > – Jack_T Jul 26 '20 at 12:14
  • 1
    @Jack_T, maybe try `df.loc[df.index.str.startswith("5|7")]` or `df.loc[df.index.str.contains("^5|^7")]`? – help-ukraine-now Jul 26 '20 at 12:21
  • the second one did the job amazingly, super grateful! did you have the chance to have a look at: https://stackoverflow.com/questions/63093396/code-does-not-work-when-converted-into-function cheers! – Jack_T Jul 26 '20 at 12:41