熊猫将列换行

时间:2019-02-08 17:11:47

标签: pandas

我有一个这样的熊猫数据框:

DATE     NAME    INCOME   EXPENSE
201811    XX      100      50

我需要像这样转置(长格式):

DATE     NAME    ATTRIBUTE  ATTRIBUTE_VALUE
201811    XX      INCOME      100
201811    XX      EXPENSE      50

我看过熊猫转置功能,但不确定如何从宽格式转换为长格式

1 个答案:

答案 0 :(得分:6)

使用pd.melt()

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

data_file = pd.read_csv('CSV/stepsgyro.csv')

# print(data_file.head())

# put in the correct data types
data_file = data_file.astype({"steps": int})
pd.to_datetime(data_file['date'])

# makes the date definitely the index at the bottom
data_file.set_index(['date'], inplace=True)

# sorts the data frame by the index
data_file.sort_values(by=['date'], inplace=True, ascending=True)
# data_file.columns.values[1] = 'date'

# plot the raw steps data
# data_file.plot()
plt.scatter(data_file.date, data_file.steps)
plt.title('Daily Steps')
plt.grid(alpha=0.3)
plt.show()

plt.close('all')

# plot the cumulative steps data
data_file = data_file.cumsum()
data_file.plot()
plt.title('Cumulative Daily Steps')
plt.grid(alpha=0.3)
plt.show()

plt.close('all')