2

For example

df = {'a': (1,2,3)}
pd.DataFrame(df)

and I want to copy the column for several times, and put them in to the same dataframe. I hope it finally becomes

    a   b   c
0   1   1   1
1   2   2   2
2   3   3   3

Codes I tried need manually name the columns. And I cannot build a loop to auto name columns.

Rick
  • 43,029
  • 15
  • 76
  • 119
Liming Zhu
  • 221
  • 1
  • 3
  • 6

3 Answers3

2

If you do not want to write by hand the alphabet, you can do:

import pandas as pd

df = {'a': (1,2,3)}
dd = pd.DataFrame(df)

numcopies = 4 #how many copies you want of the original column named 'a'
names = [chr(ord('a') + i) for i in range(1, numcopies+1)]

for n in names:
    dd[n] = dd['a']

chr() and ord() are built-in functions which comes in handy to generate sequence of letters / characters.

EDIT after comments

A more concise version of it (with no need to store the names in a variable) is:

for i in range(1, numcopies+1):
    dd[chr(ord('a') + i)] = dd['a']

EDIT: column names with more than one character

If you want to have a lot of copied columns, have a look at this answer. It is a good way to produce sequences of strings longer that 1 character with alphabet letters only based on an input number (so you do not end with strange symbols as name column).

You can do:

for i in range(1, numcopies+1):
    dd[colnum_string(i)] = dd['a']

where column_string is the function defined in the link above.

Valentino
  • 7,291
  • 6
  • 18
  • 34
  • No need to store the names. You can do directly. `for i in range(10): df[chr(ord('a') + i)] = df['a']` – vb_rises Apr 16 '19 at 17:19
2

You could use string.ascii_lowercase and DataFrame.assign for an efficient way of doing this:

from string import ascii_lowercase

df = {'a': (1,2,3)}
df = pd.DataFrame(df)

# where n is the number of columns you want
n = 5

df_new = df.assign(**{x: df.iloc[:, 0] for x in ascii_lowercase[:n]})
print(df_new)

[output]

   a  b  c  d  e
0  1  1  1  1  1
1  2  2  2  2  2
2  3  3  3  3  3
Chris Adams
  • 18,389
  • 4
  • 22
  • 39
1

You can do something like this:

names = ['b', 'c', 'd', 'e'] #names for the columns
for i in names:
    df[i] = df['a'] #assigns the columns in a loop
  • thanks very much. But If want to copy 100 times, this code dose not really help as I still have to manually type the name. – Liming Zhu Apr 16 '19 at 17:18
  • I prefer numbered columns instead of letters, so I would change it to something like this: `names = ['col' + str(i) for i in range(1, x+1, 1)]`. Here x is the number of columns you want. – Parmandeep Chaddha Apr 16 '19 at 18:58