如何获得数据框中列为字典或列表的信息?

2024-09-24 12:31:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这些信息,但无法获取列serviceTypescrowding的值:

id  name    modeName    disruptions lineStatuses    serviceTypes    crowding
0   piccadilly  Piccadilly  tube    []  []  [{'$type': 'Tfl.Api.Presentation.Entities.Line...   {'$type': 'Tfl.Api.Presentation.Entities.Crowd...
1   victoria    Victoria    tube    []  []  [{'$type': 'Tfl.Api.Presentation.Entities.Line...   {'$type': 'Tfl.Api.Presentation.Entities.Crowd...
2   bakerloo    Bakerloo    tube    []  []  [{'$type': 'Tfl.Api.Presentation.Entities.Line...   {'$type': 'Tfl.Api.Presentation.Entities.Crowd...
3   central Central tube    []  []  [{'$type': 'Tfl.Api.Presentation.Entities.Line...   {'$type': 'Tfl.Api.Presentation.Entities.Crowd.

我试过这个代码:

def split(x, index):
    try:
        return x[index]
    except:
        return None
dflines['serviceTypes'] = dflines.serviceTypes.apply(lambda x:split(x,0))
dflines['crowding'] = dflines.crowding.apply(lambda x:split(x,1))

def values(x):
    try:
        return ';'.join('{}'.format(val) for  val in x.values())
    except:
        return None
m = dflines['serviceTypes'].apply(lambda x:values(x))
dflines1 = m.str.split(';', expand=True)
dflines1.columns = dflines['serviceTypes'][0].keys()
dflines2 = dflines1[['name']]
dflines2

但我有个错误:

AttributeError                            Traceback (most recent call last)
<ipython-input-108-8f4bb6ac731a> in <module>
     14 m = dflines['serviceTypes'].apply(lambda x:values(x))
     15 dflines1 = m.str.split(';', expand=True)
---> 16 dflines1.columns = dflines['serviceTypes'][0].keys()
     17 dflines2 = dflines1[['name']]
     18 dflines2

AttributeError: 'str' object has no attribute 'keys'

有人能帮我吗?你知道吗


Tags: apireturntypeservicelinepresentationtypessplit
1条回答
网友
1楼 · 发布于 2024-09-24 12:31:04

您可以将一列拉入列表,如下所示:

service_types = dflines['serviceTypes']

第一个值现在是服务类型列表中的第一个值。你知道吗

first_value = service_types[0]

熊猫的工作方式和字典不同。我想你可能想把数据框当作字典。如果我误解或过于简单,我道歉。你知道吗

编辑:

好的,看起来服务类型(上面)是一个字典列表。写入列以便它只包含需要索引到列表中然后索引到字典中的类型。你知道吗

service_types = dflines['serviceTypes']
types_alone = []
for i in service_types:
    types_alone.append(i['$type'][0])
dflines['new_column'] = types_alone

相关问题 更多 >