gpt4 book ai didi

python - 将字典中的列表作为新列添加到 DataFrame

转载 作者:太空宇宙 更新时间:2023-11-03 12:55:31 25 4
gpt4 key购买 nike

假设我有以下 pandas DataFrame:

df = pd.DataFrame({'x': [0, 1, 2], 'y': [3, 4, 5], 'z': [6, 7, 8]})
x y z
0 0 3 6
1 1 4 7
2 2 5 8

和下面的字典:

d = {'a': [10, 10, 10], 'b': [100, 100, 100]}

将字典添加到 DataFrame 以获得以下内容的最佳方法是什么:

     x   y   z    a    b
0 0 3 6 10 100
1 1 4 7 10 100
2 2 5 8 10 100

这是我到目前为止想出的方法,但我觉得必须有更好的方法:

df_bigger = pd.concat([df, pd.DataFrame(d)], axis=1)

最佳答案

赋值与字典解包结合使用

df.assign(**d)

x y z a b
0 0 3 6 10 100
1 1 4 7 10 100
2 2 5 8 10 100

请注意,使用assign,只要列表的长度与数据帧一致,就会处理索引。

关于python - 将字典中的列表作为新列添加到 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44170132/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com