gpt4 book ai didi

python - 如何 reshape 多个时间序列信号以与 sns.tsplot 一起使用?

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

我正在尝试 reshape 数据,如下所示:

   t  y0  y1  y2
0 0 -1 0 1
1 1 0 1 2
2 2 1 2 3
3 3 2 3 4
4 4 3 4 5

变成这样的东西:

    t  trial signal  value
0 0 0 y -1
1 0 1 y 0
2 0 2 y 1
3 1 0 y 0
4 1 1 y 1
5 1 2 y 2
6 2 0 y 1
7 2 1 y 2
8 2 2 y 3
9 3 0 y 2
10 3 1 y 3
11 3 2 y 4
12 4 0 y 3
13 4 1 y 4
14 4 2 y 5

这样我就可以将其输入到 sns.tsplot 中。

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

fig = plt.figure()
num_points = 5

# Create some dummy line signals and assemble a data frame
t = np.arange(num_points)
y0 = t - 1
y1 = t
y2 = t + 1
df = pd.DataFrame(np.vstack((t, y0, y1, y2)).transpose(), columns=['t', 'y0', 'y1', 'y2'])
print(df)

# Do some magic transformations
df = pd.melt(df, id_vars=['t'])
print(df)

# Plot the time-series data
sns.tsplot(time="t", value="value", unit="trial", condition="signal", data=df, ci=[68, 95])

plt.savefig("dummy.png")
plt.close()

我希望能够实现这一点:

enter image description here

https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.tsplot.html http://pandas.pydata.org/pandas-docs/stable/reshaping.html

最佳答案

我认为你可以使用melt对于 reshape ,通过 indexing with str 获取第一个和第二个字符最后sort_values重新排序列:

df1 = pd.melt(df, id_vars=['t'])
#create helper Series
variable = df1['variable']
#extract second char, convert to int
df1['trial'] = variable.str[1].astype(int)
#extract first char
df1['signal'] = variable.str[0]
#sort values by column t, reset index
df1 = df1.sort_values('t').reset_index(drop=True)
#reorder columns
df1 = df1[['t','trial','signal','value']]
print df1
t trial signal value
0 0 0 y -1
1 0 1 y 0
2 0 2 y 1
3 1 0 y 0
4 1 1 y 1
5 1 2 y 2
6 2 0 y 1
7 2 1 y 2
8 2 2 y 3
9 3 0 y 2
10 3 1 y 3
11 3 2 y 4
12 4 0 y 3
13 4 1 y 4
14 4 2 y 5

另一种解决方案,如果 signal 列中的所有值都仅为 y:

#remove y from column name, first value of column names is same
df.columns = df.columns[:1].tolist() + [int(col[1]) for col in df.columns[1:]]
print df
t 0 1 2
0 0 -1 0 1
1 1 0 1 2
2 2 1 2 3
3 3 2 3 4
4 4 3 4 5

df1 = pd.melt(df, id_vars=['t'], var_name=['trial'])
#all values in column signal are y
df1['signal'] = 't'
#sort values by column t, reset index
df1 = df1.sort_values('t').reset_index(drop=True)
#reorder columns
df1 = df1[['t','trial','signal','value']]
print df1
t trial signal value
0 0 0 t -1
1 0 1 t 0
2 0 2 t 1
3 1 0 t 0
4 1 1 t 1
5 1 2 t 2
6 2 0 t 1
7 2 1 t 2
8 2 2 t 3
9 3 0 t 2
10 3 1 t 3
11 3 2 t 4
12 4 0 t 3
13 4 1 t 4
14 4 2 t 5

关于python - 如何 reshape 多个时间序列信号以与 sns.tsplot 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36614576/

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