Home > Back-end >  Iterating over a dataframe's columns and edit the values
Iterating over a dataframe's columns and edit the values

Time:11-24

Suppose I have the following dataframe:

test = {'col1':[{'value': '001'},{'value': False},{'value': 'abc'}]}
df = pd.DataFrame(test)

col1
0   {'value': '001'}
1   {'value': False}
2   {'value': 'abc'}

I want to iterate over col1 and only show the true values, such that I get:

col1
0    '001'
1    False
2   'abc'

I tried doing df.replace(r'{^\d\.} ', '', regex=True) which didn't work, I wonder what am I doing wrong here?

CodePudding user response:

Try:

>>> pd.DataFrame(df["col1"].tolist())
   value
0    001
1  False
2    abc

CodePudding user response:

You could also use .str:

>>> df['col1'].str['value']
0      001
1    False
2      abc
Name: col1, dtype: object

As unintuitive as it seems, .str can be used in just about any way than you'd use [] normally on. For example, the above works because this works:

item = df['col1'][0]
item['value'] # <---- Because this works, you can do `df['col1'].str['value']`

CodePudding user response:

Here is another way using map:

df['col1'].map(lambda x: list(x.values())[0])

0      001
1    False
2      abc
Name: col1, dtype: object
  • Related