熊猫从宽到长都有附加字典

时间:2019-04-29 05:23:13

标签: python pandas

我的数据框看起来像这样

>df
ds           A  B  C
01/01/2010   4  2  1
02/01/2010   2  9  3
03/01/2010   1  3  0

其中A和B属于类别1,C属于类别2。

我想将其转换为:

ds           Category  Company  Value
01/01/2010      1         A      4
01/01/2010      1         B      2
01/01/2010      2         C      1

以此类推,以便以后绘制。

2 个答案:

答案 0 :(得分:2)

使用DataFrame.melt

df['ds'] = pd.to_datetime(df['ds'], format='%d/%m/%Y')

df = df.melt('ds', var_name='Company')

如果可能有多个类别,请创建字典并按Series.map创建新列:

d = {1:['A','B'], 2:['C']}
#swap key values in dict
#http://stackoverflow.com/a/31674731/2901002
d1 = {k: oldk for oldk, oldv in d.items() for k in oldv}

df['Category'] = df['Company'].map(d1)

#alternative1
#df['Category'] = np.where(df['Company'] == 'C', 2, 1)
#alternative2
#df['Category'] = np.where(df['Company'].isin(['A','B']), 1, 2)

df = df.sort_values(['ds','Company']).reset_index(drop=True)

或将DataFrame.set_indexDataFrame.stack

df['ds'] = pd.to_datetime(df['ds'], format='%d/%m/%Y')

df = df.set_index('ds').stack().rename_axis(('ds','Company')).reset_index(name='value')
df['Category'] = np.where(df['Company'] == 'C', 2, 1)

print (df)
          ds Company  value  Category
0 2010-01-01       A      4         1
1 2010-01-01       B      2         1
2 2010-01-01       C      1         2
3 2010-01-02       A      2         1
4 2010-01-02       B      9         1
5 2010-01-02       C      3         2
6 2010-01-03       A      1         1
7 2010-01-03       B      3         1
8 2010-01-03       C      0         2

答案 1 :(得分:1)

我们可以使用pd.melt后跟 np.where

df2 = pd.melt(df, id_vars=['ds'], value_vars=['A', 'B', 'C'])

df2['Category'] = np.where((df2['variable'] == 'A') | (df2['variable'] == 'B'), 1, 2)