Python 基于条件的熊猫转置
我有一个数据帧Python 基于条件的熊猫转置,python,pandas,Python,Pandas,我有一个数据帧 Key Col1 Col2 Col3 Colother 1 11 12 0 'a' 2 0 21 31 'b' 3 5 6 7 'c' 预期产量 Key Col1 Col2 Col3 Colother Colnew 1 11 12 0 'a' 11 1 11 12 0 'a' 12 2 0
Key Col1 Col2 Col3 Colother
1 11 12 0 'a'
2 0 21 31 'b'
3 5 6 7 'c'
预期产量
Key Col1 Col2 Col3 Colother Colnew
1 11 12 0 'a' 11
1 11 12 0 'a' 12
2 0 21 31 'b' 21
2 0 21 31 'b' 31
3 5 6 7 'c' 5
3 5 6 7 'c' 6
3 5 6 7 'c' 7
我试过使用df.T
,但选项有限。因为我不想为0
列创建行。现在我只剩下对行进行迭代了。使用:
也可以在查询中进行筛选
,谢谢@Scott Boston的建议:
df1 = df.melt(['Key','Colother'], value_name='Colnew').drop('variable', axis=1)
df = df.merge(df1.query('Colnew != 0'))
print (df)
Key Col1 Col2 Col3 Colother Colnew
0 1 11 12 0 'a' 11
1 1 11 12 0 'a' 12
2 2 0 21 31 'b' 21
3 2 0 21 31 'b' 31
4 3 5 6 7 'c' 5
5 3 5 6 7 'c' 6
6 3 5 6 7 'c' 7
尝试使用
agg
然后explode
df['Colnew'] = df[['Col1','Col2','Col3']].agg(list,1)
df = df.explode('Colnew').loc[lambda x : x['Colnew']!=0]
df
Out[364]:
Key Col1 Col2 Col3 Colother Colnew
0 1 11 12 0 'a' 11
0 1 11 12 0 'a' 12
1 2 0 21 31 'b' 21
1 2 0 21 31 'b' 31
2 3 5 6 7 'c' 5
2 3 5 6 7 'c' 6
2 3 5 6 7 'c' 7
让我们试试
stack
和join
:
c = ['Col1', 'Col2', 'Col3']
df.join(df[c].mask(df[c].eq(0)).stack().droplevel(1).rename('ColNew'))
您可以使用join来实现这一点
将熊猫作为pd导入
将numpy作为np导入
x=[
{
“key”:1,“col1”:11,“col2”:12,“col3”:0,“colother”:“a”
},
{
“key”:2,“col1”:0,“col2”:21,“col3”:31,“colother”:“b”
}, {
“key”:3,“col1”:5,“col2”:6,“col3”:7,“colother”:“c”
},
]
df=pd.DataFrame(x)
打印(df.join(df[[“col1”、“col2”、“col3”]].stack().droplevel(1).重命名('colnew')。替换(0,np.nan).dropna())
输出:
col1 col2 col3 colother key colnew
0 11 12 0 a 1 11.0
0 11 12 0 a 1 12.0
1 0 21 31 b 2 21.0
1 0 21 31 b 2 31.0
2 5 6 7 c 3 5.0
2 5 6 7 c 3 6.0
2 5 6 7 c 3 7.0
阿格,我还是比你慢
df.melt(['Key','Colother'])。query('value!=0')。merge(df)
比我快45秒。:-)保持安全和健康,我的朋友。
Key Col1 Col2 Col3 Colother ColNew
0 1 11 12 0 'a' 11
0 1 11 12 0 'a' 12
1 2 0 21 31 'b' 21
1 2 0 21 31 'b' 31
2 3 5 6 7 'c' 5
2 3 5 6 7 'c' 6
2 3 5 6 7 'c' 7
col1 col2 col3 colother key colnew
0 11 12 0 a 1 11.0
0 11 12 0 a 1 12.0
1 0 21 31 b 2 21.0
1 0 21 31 b 2 31.0
2 5 6 7 c 3 5.0
2 5 6 7 c 3 6.0
2 5 6 7 c 3 7.0