gpt4 book ai didi

python - 将 pandas pd 转换为 numpy 数组并返回

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

我想要的是将 numpy 数组转换为 pandas 数据帧。

df.head()
A B C D
0 34 howdy cow meting
1 23 cow me howdy

标记这个 df 之后

df.head()
A B C D
0 34 1 2 3
1 23 2 4 1

将 df 转换为 numpy 数组以使用 KMeans 进行分析 numpy 数组

   array [[34 ,1, 2, 3],
[23 ,2, 4, 1]]

问题如何将其转换回第一个 df即比较数组的索引和 pandas 的索引并获取行值

最佳答案

我想你可以使用 values用于转换为 numpy array 然后 DataFrame构造函数:

arr = df.values
print (arr)
[[34 1 2 3]
[23 2 4 1]]

print (pd.DataFrame(arr))
0 1 2 3
0 34 1 2 3
1 23 2 4 1
print (pd.DataFrame(arr, index=df.index, columns=df.columns))
A B C D
0 34 1 2 3
1 23 2 4 1

关于python - 将 pandas pd 转换为 numpy 数组并返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40972147/

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