Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concat column Y to column X and replicate values Z in pandas dataframe?

Tags:

python

pandas

I have a pandas DataFrame with three columns:

     X    Y    Z
0    1    4    True
1    2    5    True
2    3    6    False

How do I make it so that I have two columns X and Z with values:

    X    Z
0   1    True
1   2    True
2   3    False
3   4    True
4   5    True
5   6    False
like image 454
RogerKint Avatar asked Oct 23 '25 19:10

RogerKint


2 Answers

you can melt:

In [41]: df.melt(id_vars="Z", value_vars=["X", "Y"], value_name="XY")[["XY", "Z"]]
Out[41]:
   XY      Z
0   1   True
1   2   True
2   3  False
3   4   True
4   5   True
5   6  False
  • identifier variable is "Z": it will be repeated as necessary against value variables...
  • ...which are X and Y
  • name X and Y's together column to "XY", and select that and "Z" at the end

(you can chain .rename(columns={"XY": "X"}) if you want that column to be named X again.)

like image 108
Mustafa Aydın Avatar answered Oct 25 '25 10:10

Mustafa Aydın


Another possible solution, based on pandas.concat:

pd.concat([df[['X','Z']], df[['Y','Z']].rename({'Y': 'X'}, axis=1)])

Output:

   X      Z
0  1   True
1  2   True
2  3  False
0  4   True
1  5   True
2  6  False
like image 28
PaulS Avatar answered Oct 25 '25 10:10

PaulS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!