I have a dataframe df
as below:
Name Count
[{‘text’: ‘Server1.com’}] [{‘text’: 1}]
[{‘text’: ‘Server3.com’}] [{‘text’: 1}]
[{‘text’: ‘Server2.com’}] [{‘text’: 22}]
I want to transform this into:
Name Count
Server1.com 1
Server3.com 1
Server2.com 22
What I am trying is this:
df1 = pd.DataFrame()
for i in range(df.shape[1]):
df1 = pd.concat([df1, df[i].iloc[0:][0][‘text’]], axis=1)
But it gives me TypeError: list indices must be integers or slices, not str
When I checked, df[0].iloc[0][0][‘text’]
it rightly transforms the element of row1,column1
Does iloc
Not work with slices [0:]
? Is there a simpler way to do it ?
Please note, my dataframe would not always have fixed number of rows or columns - 3 and 2 respectively - as shown in my example above. But each field would always have values in the form of [{‘text’: value}]
i.e list of length 1, and the element is always a dictionary with key as ‘text’
CodePudding user response:
An easy option is to use applymap
:
out = df.applymap(lambda x: x[0]['text'])
Another option:
out = df.apply(lambda s: s.str[0].str['text'])
Output:
Name Count
0 Server1.com 1
1 Server3.com 1
2 Server2.com 22
Used input:
df = pd.DataFrame({'Name': [[{'text': 'Server1.com'}],
[{'text': 'Server3.com'}],
[{'text': 'Server2.com'}]],
'Count': [[{'text': 1}],
[{'text': 1}],
[{'text': 22}]]
})