gpt4 book ai didi

python - Pandas 将字典连接到数据框

转载 作者:行者123 更新时间:2023-11-28 20:40:07 25 4
gpt4 key购买 nike

我有一个现有的数据框,我正在尝试连接一个字典,其中字典的长度与数据框不同

         A        B        C
0 0.46324 0.32425 0.42194
1 0.10596 0.35910 0.21004
2 0.69209 0.12951 0.50186
3 0.04901 0.31203 0.11035
4 0.43104 0.62413 0.20567
5 0.43412 0.13720 0.11052
6 0.14512 0.10532 0.05310

test = {"One": [0.23413, 0.19235, 0.51221], "Two": [0.01293, 0.12235, 0.63291]}

我正在尝试将 test 添加到 df,同时将键更改为 "D""C" 我看过 https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.htmlhttps://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html这表明我应该能够将字典连接到数据框

我试过:

pd.concat([df, test], axis=1, ignore_index=True, keys=["D", "E"])
pd.concat([df, test], axis=1, ignore_index=True)

但我没有任何运气,我想要达到的结果是

         A        B        C        D        E
0 0.46324 0.32425 0.42194 0.23413 0.01293
1 0.10596 0.35910 0.21004 0.19235 0.12235
2 0.69209 0.12951 0.50186 0.51221 0.63291
3 0.04901 0.31203 0.11035 NaN NaN
4 0.43104 0.62413 0.20567 NaN NaN
5 0.43412 0.13720 0.11052 NaN NaN
6 0.14512 0.10532 0.05310 NaN NaN

最佳答案

假设您要将它们添加为行:

>>> pd.concat([df, pd.DataFrame(test.values(), columns=df.columns)], ignore_index=True)
A B C
0 0.46324 0.32425 0.42194
1 0.10596 0.35910 0.21004
2 0.69209 0.12951 0.50186
3 0.04901 0.31203 0.11035
4 0.43104 0.62413 0.20567
5 0.43412 0.13720 0.11052
6 0.14512 0.10532 0.05310
7 0.01293 0.12235 0.63291
8 0.23413 0.19235 0.51221

如果添加为新列:

df_new = pd.concat([df, pd.DataFrame(test.values()).T], ignore_index=True, axis=1)
df_new.columns = \
df.columns.tolist() + [{'One': 'D', 'Two': 'E'}.get(k) for k in test.keys()]

>>> df_new
A B C E D
0 0.46324 0.32425 0.42194 0.01293 0.23413
1 0.10596 0.35910 0.21004 0.12235 0.19235
2 0.69209 0.12951 0.50186 0.63291 0.51221
3 0.04901 0.31203 0.11035 NaN NaN
4 0.43104 0.62413 0.20567 NaN NaN
5 0.43412 0.13720 0.11052 NaN NaN
6 0.14512 0.10532 0.05310 NaN NaN

字典中不能保证顺序(例如 test),因此新的列名实际上需要映射到键。

关于python - Pandas 将字典连接到数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36366036/

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