gpt4 book ai didi

python - 如何快速从 pandas df 读取和绘制数组

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

我在 pandas 中有以下数据帧,其中包含使用 pd.read_sql() 直接从 sqlite 数据库读取它的数组:

      ArrayID  Value
0 0 0
1 0 1
2 0 2
3 0 3
4 0 4
5 0 5
6 1 0
7 1 1
8 1 2
9 1 3

我想知道一种快速获取数组的方法,以便我可以绘制它:

Array0 [0,1,2,3,4,5]

Array1 [0,1,2,3]

我能想到的唯一方法是(当表有 1000 个数组,且数组长度各不相同且最大长度为 500 时,速度非常慢):

import pandas as pd    
import matplotlib.pyplot as plt

# loop on
for id in df.ArrayID:
array = df.loc[df["ArrayID"]==id, "Value"].values()
plt.plot(array)

plt.show()

或者是 matplotlib 出了问题吗?

最佳答案

使用groupby在一次调用中获取组,(而不是多次调用df.locdf['ArrayID'] == id):

for aid, grp in df.groupby(['ArrayID']):
plt.plot(grp['Value'].values)
<小时/>

另请注意,plt.plot 速度不是很快。调用它 1000 次可能会感觉很慢。而且,1000 行的图可能看起来不太容易理解。您可能需要重新考虑您希望可视化的数量(可能通过聚类或聚合)。

<小时/>
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

N, M = 500, 1000
data = np.row_stack([np.column_stack(np.broadcast_arrays(i,
(np.random.random(np.random.randint(N))-0.5).cumsum())) for i in range(M)])
df = pd.DataFrame(data, columns=['ArrayID', 'Value'])
for aid, grp in df.groupby(['ArrayID']):
plt.plot(grp['Value'].values)
plt.show()

enter image description here

关于python - 如何快速从 pandas df 读取和绘制数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38041544/

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