0

I've had issues finding a concise way to append a series to each row of a dataframe, with the series labels becoming new columns in the df. All the values will be the same on each of the dataframes' rows, which is desired.

I can get the effect by doing the following:

df["new_col_A"] = ser["new_col_A"]
.....
df["new_col_Z"] = ser["new_col_Z"]

But this is so tedious there must be a better way, right?

5
  • Hello friend, mind explaining what exactly you want to do, you just want a quick code that can append multiple series at once? Commented Oct 21, 2022 at 0:56
  • pd.concat([df, ser], axis=1)? Commented Oct 21, 2022 at 1:01
  • Hey, sorry if it was vague. What I'm hoping for is something which takes a dataframe like this: df = pd.DataFrame([[1, 2], [1, 3], [4, 6]], columns=['A', 'B']) which when "concated" with a series like this: ser = pd.Series(["a","b"],index=["C",D"]) will give a result like this: df = pd.DataFrame([[1, 2,"a","b"], [1, 3,"a","b"], [4, 6,"a","b"]], columns=['A', 'B','C','D']) Commented Oct 21, 2022 at 1:23
  • I found the suggestion from @BeRT2me, simply adds it to the bottom and introduces NaNs all over the table. Commented Oct 21, 2022 at 1:27
  • 1
    Add all of that as an Edit to your question, not as a comment~ Commented Oct 21, 2022 at 1:28

1 Answer 1

1

Given:

# df

   A  B
0  1  2
1  1  3
2  4  6

# ser

C    a
D    b
dtype: object

Doing:

df[ser.index] = ser
print(df)

Output:

   A  B  C  D
0  1  2  a  b
1  1  3  a  b
2  4  6  a  b
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks heaps, and also thanks for the tip about further comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.