1

I have a list of integers x and I am trying to create a new column to an existing dataframe that has each of the x[0] ... x[1345] in the appropriate place.

This is what I did:

i = 0
while i < len(x):
    df['Paystrings'] = x[i]
    i = i + 1
df.head()

But I only get this:

enter image description here

Which is just the last element of x

  • You overwrite `df['Paystrings']` in each iteration. What's your desired output? Do you want to create 1346 _new_ columns? – pault Nov 26 '18 at 21:20
  • That's because you are redefining the column with the value `x[i]`. So at the end of the loop, that will be `x[-1]` for the whole column – C.Nivs Nov 26 '18 at 21:21
  • Yes because df['Paystrings'] = x[i] sets the whole column to the value x[i] – MisterMonk Nov 26 '18 at 21:21
  • @pault I want to create a new column called Paystring, then for each row in that coilumn put x[0] in the first row x[1] in the second etc... does that make sense?' –  Nov 26 '18 at 21:22
  • I'd probably wrap `x` in a `Series` to stick into the Dataframe – C.Nivs Nov 26 '18 at 21:23
  • Yes, now I understand. Here is a dupe: [Add column in dataframe from list](https://stackoverflow.com/questions/26666919/add-column-in-dataframe-from-list/38490727) – pault Nov 26 '18 at 21:24

1 Answers1

0

If you don't have a index explizit set in the creation you can do this:

df['Paystrings'] = pd.Series(x)

Elsewise you can reset the index, then all elements have the number like they are sorted in this moment.

df.reset_index()
MisterMonk
  • 327
  • 1
  • 9