键和值位于单独的列中,我想创建具有相应值的列

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

抱歉标题令人困惑!我的数据框中有以下列:

Column A                         Column B
['Dogs','Cats','Horses']       [0.5,0.25,0.25]    
['Dogs']                       [1.0]   
['Cats','Horses']             [0.75,0.25]   

我想要的输出是:

Dogs                        Cats                        Horses
0.5                         0.25                        0.25   
1.0                         0                           0  
0                           0.75                        0.25

提前谢谢您! :)

我尝试了以下代码:

keys = set([key for row in df['column_a'] for key in row])

for key in keys:
    df[key] = 0.0

for i, row in df.iterrows():
    for key, value in zip(row['column_a'], row['column_b']):
        if isinstance(value, list):
            for demography, score in zip(key, value):
                df.at[i, demography] = score
        else:
            df.at[i, key] = value

df.drop(columns=['column_a', 'column_b'], inplace=True)

并收到错误“TypeError:‘float’对象不可迭代”

python typeerror key-value
1个回答
0
投票

错误“TypeError: ‘float’ object is not iterable”是因为代码试图迭代 float,这是不可能的。

问题出在这行:

for demography, score in zip(key, value):

这里,它尝试迭代

key
value
,但在某些情况下
value
不是列表(即浮点数),这会引发错误。

您可以修改代码以在尝试迭代之前检查

value
是否是一个列表:

for i, row in df.iterrows():
    for key, value in zip(row['column_a'], row['column_b']):
        if isinstance(value, list):
            for demography, score in zip(key, value):
                df.at[i, demography] = score
        else:
            df.at[i, key] = value

这样,如果

value
是一个列表,它将迭代它,如果不是,它将直接分配值。

此外,您可能想使用 pandas 的内置函数以获得更好的性能:

df_new = pd.DataFrame(df['Column B'].tolist(), index=df.index, columns=df['Column A'].tolist())
df_new = df_new.fillna(0)

这将创建一个具有您所需格式的新 DataFrame。

© www.soinside.com 2019 - 2024. All rights reserved.