columns = ['a', "b","cin",'cout', 'din', 'dout']
rows = [[1 , 1, 3, 4, 2, 3], [2,3,3,1, 8 , 4], [3,1,3,1, 2, 1]]
dff1 = pd.DataFrame(rows, columns=columns)
结果
如何将输出设为6行,其中Cin,Cout和din,dout被视为带有a和b的2个特殊行?还有一个添加的列输入/输出.
一般来说,我需要操纵上面的数据框来带来下面的附件
解决方法:
你可以使用lreshape:
df = pd.lreshape(dff, {'c':['c1','c2'], 'd':['d1','d2']})
print (df)
a b c d
0 1 1 3 2
1 2 3 3 8
2 3 1 3 2
3 1 1 4 3
4 2 3 1 4
5 3 1 1 1
dff = dff.reset_index()
a = (pd.wide_to_long(dff, stubnames=['c', 'd'], i='index', j='B')
.reset_index(drop=True)
.reindex(columns=['a','b','c', 'd']))
print (a)
a b c d
0 1 1 3 2
1 2 3 3 8
2 3 1 3 2
3 1 1 4 3
4 2 3 1 4
5 3 1 1 1
编辑:如果还希望列使用melt
,extract
,assign
和sort_values
:
a = dff1.melt(id_vars=['a','b'],value_vars=['cin','cout'],value_name = 'c',var_name='in/out')
b = dff1.melt(id_vars=['a','b'],value_vars=['din','dout'],value_name = 'd',var_name='in/out')
a['in/out'] = a['in/out'].str.extract('(in|out)', expand=False)
b['in/out'] = b['in/out'].str.extract('(in|out)', expand=False)
print (a)
a b in/out c
0 1 1 in 3
1 2 3 in 3
2 3 1 in 3
3 1 1 out 4
4 2 3 out 1
5 3 1 out 1
print (b)
a b in/out d
0 1 1 in 2
1 2 3 in 8
2 3 1 in 2
3 1 1 out 3
4 2 3 out 4
5 3 1 out 1
c = a.assign(d=b['d']).sort_values(['a','b'])
#same as
#c = pd.merge(a,b).sort_values(['a','b'])
print (c)
a b in/out c d
0 1 1 in 3 2
3 1 1 out 4 3
1 2 3 in 3 8
4 2 3 out 1 4
2 3 1 in 3 2
5 3 1 out 1 1
为大熊猫0.15.0重写的解决方案:
a=pd.melt(dff1,id_vars=['a','b'],value_vars=['cin','cout'],value_name='c',var_name='in/out')
b=pd.melt(dff1,id_vars=['a','b'],value_vars=['din','dout'],value_name='d',var_name='in/out')
a['in/out'] = a['in/out'].str.extract('(in|out)')
b['in/out'] = b['in/out'].str.extract('(in|out)')
c = pd.merge(a,b).sort_values(['a','b'])
来自wen删除答案的另一个解决方案 – 需要replace
字符串数字然后使用wide_to_long
,去年map
:
#define columns
L = ['in','out']
d = dict(enumerate(L))
d1 = {v: str(k) for k, v in d.items()}
print (d)
{0: 'in', 1: 'out'}
print (d1)
{'out': '1', 'in': '0'}
dff1.columns = dff1.columns.to_series().replace(d1,regex=True)
a = pd.wide_to_long(dff1, stubnames=['c', 'd'], j='in/out', i=['a','b']).reset_index()
a['in/out'] = a['in/out'].astype(int).map(d)
a = a[['a','b','c','d','in/out']]
print (a)
a b c d in/out
0 1 1 3 2 in
1 1 1 4 3 out
2 2 3 3 8 in
3 2 3 1 4 out
4 3 1 3 2 in
5 3 1 1 1 out
编辑:
对于还原过程使用:
df = df.set_index(['a', 'b', 'in/out']).unstack()
df.columns = df.columns.map(''.join)
df = df.reset_index()
print (df)
a b cin cout din dout
0 1 1 3 4 2 3
1 2 3 3 1 8 4
2 3 1 3 1 2 1
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。