Pandas .iloc[]无法处理索引范围



我有一个数据框df如下:

Name               Count
[{‘text’: ‘Server1.com’}]       [{‘text’: 1}]
[{‘text’: ‘Server3.com’}]       [{‘text’: 1}]
[{‘text’: ‘Server2.com’}]      [{‘text’: 22}]

我想把它转换成:

Name      Count
Server1.com          1        
Server3.com          1
Server2.com         22

我要做的是:

df1 = pd.DataFrame()
for i in range(df.shape[1]):
df1 = pd.concat([df1, df[i].iloc[0:][0][‘text’]], axis=1)

结果是TypeError: list indices must be integers or slices, not str

当我检查df[0].iloc[0][0][‘text’]时,它正确地转换了row1,column1的元素

iloc不能与切片[0:]一起工作吗?有没有更简单的方法?

请注意,我的数据框架并不总是有固定数量的行或列——分别是3行和2列——正如我上面的例子所示。但是每个字段的值总是以[{‘text’: value}]的形式出现,即长度为1的列表,元素总是一个键为' text '的字典

一个简单的选择是使用applymap:

out = df.applymap(lambda x: x[0]['text'])

另一种选择:

out = df.apply(lambda s: s.str[0].str['text'])
输出:

Name  Count
0  Server1.com      1
1  Server3.com      1
2  Server2.com     22

输入:使用

df = pd.DataFrame({'Name': [[{'text': 'Server1.com'}],
[{'text': 'Server3.com'}],
[{'text': 'Server2.com'}]],
'Count': [[{'text': 1}],
[{'text': 1}],
[{'text': 22}]]
})

最新更新