gpt4 book ai didi

python - Pandas wide to long 附加字典

转载 作者:太空宇宙 更新时间:2023-11-04 11:21:29 26 4
gpt4 key购买 nike

我的数据框是这样的

>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

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

最佳答案

使用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

关于python - Pandas wide to long 附加字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55897389/

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