Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all columns in pandas dataframe with one column

Tags:

python

pandas

I have a pandas dataframe as follows:

    0    1    2    3    4
0   a    b    c    d    e
1   f    g    h    i    j
2   k    l    m    n    o
3   p    q    r    s    t

I want to replace all the columns in the dataframe with the values in column 1, so the result would be

    0    1    2    3    4
0   b    b    b    b    b
1   g    g    g    g    g
2   l    l    l    l    l
3   q    q    q    q    q

How would you do it pandas?

like image 547
Ted Avatar asked Dec 19 '22 07:12

Ted


1 Answers

Consider the dataframe df

df = pd.DataFrame(np.array(list('abcdefghijklmnopqrst')).reshape(-1, 5))
print(df)

   0  1  2  3  4
0  a  b  c  d  e
1  f  g  h  i  j
2  k  l  m  n  o
3  p  q  r  s  t

Reconstruct

pd.DataFrame(
    np.column_stack([df[1].values] * len(df.columns)),
    df.index, df.columns
)

   0  1  2  3  4
0  b  b  b  b  b
1  g  g  g  g  g
2  l  l  l  l  l
3  q  q  q  q  q
like image 162
piRSquared Avatar answered Dec 21 '22 11:12

piRSquared