使用 Pandas 将数据框转换为字典时保留数字列表(停止转换为字符串)

问题描述 投票:0回答:2

我想将熊猫数据框转换成字典。该数据集有许多存储为列表的变量,即 [0,2,5,6]。当我使用 pd.to_dict 将数据框转换为字典时,这些列表存储为字符串而不是数字列表(即'[0,2,5,6]'而不是[0,2,5,6])。有没有一种简单的方法可以执行此操作,或者我是否需要在转换后遍历字典列表?如果需要,将如何执行该迭代?

NDF = DF.to_dict(orient = 'records')

电流输出:

..., 'Description': 'Version 5.1', 'Coord': '[128, 32]', 'Elev': '[0.19, 0.43]', 'Strength': 150,...

期望的输出:

..., 'Description': 'Version 5.1', 'Coord': [128, 32], 'Elev': [0.19, 0.43], 'Strength': 150.0, ...
python pandas string dataframe
2个回答
0
投票

看看对你有没有帮助:

a = ''
a = a.split()
a[0] = a[0][1:]
for i in range(len(a)):
    a[i] = a[i][:-1]
    a[i] = int(a[i])
print(a)

0
投票

您可以像这样迭代当前输出(假设没有嵌套列表作为任何键的值)

current_output = {
    'Description': 'Version 5.2',
    'Coord': '[128, 32]',
    'Elev': '[0.19, 0.43]',
    'Strength': 150
    }

for k, v in current_output.items():
    if type(current_output[k]) == str and current_output[k].startswith('['):
        current_output[k] = [float(i) for i in current_output[k][1:-1].split(',')]

print(current_output)
>> {'Description': 'Version 5.2', 'Coord': [128.0, 32.0], 'Elev': [0.19, 0.43], 'Strength': 150}
© www.soinside.com 2019 - 2024. All rights reserved.