我有一个 Pandas DataFrame,其中包含不同时间(行)和特定垂直位置(列名称)的位移。目标是绘制给定时间(系列)内垂直位置(y 轴)的位移(x 轴)。
根据下一个示例(时间 = 0、1、2、3、4,垂直位置 = 0.5、1.5、2.5、3.5),如何绘制时间 0 和 3 的位移?
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(88)
df = pd.DataFrame({
'time': np.arange(0, 5, 1),
'0.5': np.random.uniform(-1, 1, size = 5),
'1.5': np.random.uniform(-2, 2, size = 5),
'2.5': np.random.uniform(-3, 3, size = 5),
'3.5': np.random.uniform(-4, 4, size = 5),
})
df = df.set_index('time')
最佳答案
您可以过滤数据框以仅包含所需的行。通过使用位置索引
filtered = df.iloc[[0,3],:]
或者通过使用数据帧的实际索引,
filtered = df.iloc[(df.index == 3) | (df.index == 0),:]
然后您可以像这样绘制散点图:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(88)
df = pd.DataFrame({
'time': np.arange(0, 5, 1),
'0.5': np.random.uniform(-1, 1, size = 5),
'1.5': np.random.uniform(-2, 2, size = 5),
'2.5': np.random.uniform(-3, 3, size = 5),
'3.5': np.random.uniform(-4, 4, size = 5),
})
df = df.set_index('time')
filtered_df = df.iloc[[0,3],:]
#filtered_df = df.iloc[(df.index == 3) | (df.index == 0),:]
loc = list(map(float, df.columns))
fig, ax = plt.subplots()
for row in filtered_df.iterrows():
ax.scatter(row[1], loc, label=row[1].name)
plt.legend()
plt.show()
关于python - Pandas Dataframe 将行绘制为 x 值,将列标题绘制为 y 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43606652/