0

I have to change string to list that contains dicts. When I try to make eval function on one discrite value in my dataframe, the value perfectly converts. Problem is when when I want to make it on each row in the loop.

In:

df_clean['CalculatedData.AnchorLayoutPoints'][234]

Out:

"[{'X': -114.3, 'Y': -114.3, 'IsSlotted': False}, {'X': 114.3, 'Y': -114.3, 'IsSlotted': False}, {'X': -114.3, 'Y': 114.3, 'IsSlotted': False}, {'X': 114.3, 'Y': 114.3, 'IsSlotted': False}]"

In:

list(eval(df_clean['CalculatedData.AnchorLayoutPoints'][234]))

Out:

[{'X': -114.3, 'Y': -114.3, 'IsSlotted': False},
 {'X': 114.3, 'Y': -114.3, 'IsSlotted': False},
 {'X': -114.3, 'Y': 114.3, 'IsSlotted': False},
 {'X': 114.3, 'Y': 114.3, 'IsSlotted': False}]

In:

for x in range(df_clean['CalculatedData.AnchorLayoutPoints'].shape[0]):
    string = df_clean['CalculatedData.AnchorLayoutPoints'][x]
    df_clean['CalculatedData.AnchorLayoutPoints'][x] = list(eval(string))

In:

df_clean['CalculatedData.AnchorLayoutPoints'][234]

Out:

"[{'X': -114.3, 'Y': -114.3, 'IsSlotted': False}, {'X': 114.3, 'Y': -114.3, 'IsSlotted': False}, {'X': -114.3, 'Y': 114.3, 'IsSlotted': False}, {'X': 114.3, 'Y': 114.3, 'IsSlotted': False}]"

What's wrong here?

D4w1d
  • 125
  • 1
  • 7
  • `df_clean['CalculatedData.AnchorLayoutPoints'][x] = ...` should be giving a `SettingWithCopyWarning` no? [How to deal with SettingWithCopyWarning in Pandas](https://stackoverflow.com/q/20625582/15497888) note the answer outlines that setting on a copy will not reflect in the DataFrame. – Henry Ecker Dec 08 '21 at 15:04
  • Yes, it is. How to obey it? – D4w1d Dec 08 '21 at 15:05
  • 1
    Something like `df_clean.loc[x, 'CalculatedData.AnchorLayoutPoints'] = list(eval(string))`. But something like `df_clean['CalculatedData.AnchorLayoutPoints'] = df_clean['CalculatedData.AnchorLayoutPoints'].apply(eval)` instead of the loop might be better overall. – Henry Ecker Dec 08 '21 at 15:07
  • Thanks a lot! Second option works perfectly. – D4w1d Dec 08 '21 at 15:12

0 Answers0