gpt4 book ai didi

python - 从返回元组的函数创建新的 pandas 数据框列

转载 作者:行者123 更新时间:2023-12-02 06:03:27 25 4
gpt4 key购买 nike

我有一个返回元组的函数:

def pwrs(x):
return x*x, x*x*x, x*x*x*x

我想将此函数应用于名为 data 的单列数据框:

+-------+
| x |
+-------+
| 1 |
| 2 |
| 3 |
| 4 |
+-------+

并根据函数返回元组返回一个包含新列的新数据框:

+---+------+------+------+
| x | x^2 | x^3 | x^4 |
+---+------+------+------+
| 1 | 1 | 1 | 1 |
| 2 | 4 | 8 | 16 |
| 3 | 9 | 27 | 81 |
| 4 | 16 | 64 | 256 |
+---+------+------+------+

遍历行并应用函数:

for _, row in data.iterrows():
print(pwrs(row['x']))

不知道如何从这里取得进展......

最佳答案

广义

c = np.arange(1, 5)
pd.DataFrame(df.to_numpy() ** c, df.index, c).add_prefix('x^')

x^1 x^2 x^3 x^4
0 1 1 1 1
1 2 4 8 16
2 3 9 27 81
3 4 16 64 256

关于python - 从返回元组的函数创建新的 pandas 数据框列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58884831/

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