5
votes

Hey guys i need some help with a Problem in handling Panda dataframes. Here is the Code:

df.drop(df.index[0], inplace=True)
df.columns = ['Mic. No.', 'X', 'Y', 'Z', 'Re. Pre.', 'Im. Pre.']
df['Pre'] = df['Re. Pre.'] + df['Im. Pre.'] * 1j
df.drop(['Mic. No.', 'Re. Pre.', 'Im. Pre.'], axis=1, inplace=True)

if z != 0:
   df = df.loc(df['Z'] == z)

i loaded an excel sheet in a panda dataframe. Now after some preprocessing the dataframe is in the following form:

          X         Y     Z                       Pre
  1      0.16      0.16  0.05   (1.0048704-0.51310315j)
  2      0.16     -0.16  0.05   (0.24814222-1.6094971j)
  3     -0.16      0.16  0.05   (0.24815122-1.6094059j)
  4     -0.16     -0.16  0.05   (1.0048704-0.51310315j)
  5 -0.154993  0.154993  0.05  (-0.13939651-1.7231593j)

now i want to delete all columns in the dataframe witch dont have the Value z in the column "Z". I get the error: "TypeError:'Series' objects are mutable, thus they cannot be hashed". I dont know what to do because how i see it its exacly the same like in the pandas documentary.https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html :

df.loc[df['shield'] > 6]
               max_speed  shield
 sidewinder          7       8

please i need your help.

Thanks ahead!

2
i got a solution: df = df[df['Z'] == z] But can someone explain why the other way wont work? - Samuel K.
Sorry, my answer was not what you need? - Mehdi Golzadeh
it was! but as i said i got a solution and from this point i was more interested in the reson my first attempt didnt work. - Samuel K.
Samuel, I also was stuck with same eror, it seems not intuitive. The issue is that your initial code created circular reference, changing values that affected the selection. So proper solution is to create mask first and then apply change. See more details in this answer: stackoverflow.com/a/49356823/10396469. mask = df[df['feature']==0].index; df.loc[mask, 'feature'] = z - Poe Dator

2 Answers

2
votes

you can also do it with lambda expression:

df = df[lambda x: x['Z'] == z]
2
votes

You can use square brackets with df.loc:

df = df.loc[df['Z'] == z]