How do you concatenate two single rows in pandas?

Viewed 195

I am trying to select a bunch of single rows in bunch of dataframes and trying to make a new data frame by concatenating them together.

Here is a simple example

x=pd.DataFrame([[1,2,3],[1,2,3]],columns=["A","B","C"])

   A  B  C
0  1  2  3
1  1  2  3


a=x.loc[0,:]

A    1
B    2
C    3
Name: 0, dtype: int64

b=x.loc[1,:]
A    1
B    2
C    3
Name: 1, dtype: int64

c=pd.concat([a,b])

I end up with this:

A    1
B    2
C    3
A    1
B    2
C    3
Name: 0, dtype: int64

Whearas I would expect the original data frame:

   A  B  C
0  1  2  3
1  1  2  3

I can get the values and create a new dataframe, but this doesn't seem like the way to do it.

3 Answers

Since you are slicing by index I'd use .iloc and then notice the difference between [[]] and [] which return a DataFrame and Series*

a = x.iloc[[0]]
b = x.iloc[[1]]

pd.concat([a, b])
#   A  B  C
#0  1  2  3
#1  1  2  3

To still use .loc, you'd do something like

a = x.loc[[0,]]
b = x.loc[[1,]]

*There's a small caveat that if index 0 is duplicated in x then x.loc[0,:] will return a DataFrame and not a Series.

If you want to concat two series vertically (vertical stacking), then one option is a concat and transpose.

Another is using np.vstack:

pd.DataFrame(np.vstack([a, b]), columns=a.index)

   A  B  C
0  1  2  3
1  1  2  3

It looks like you want to make a new dataframe from a collection of records. There's a method for that:

import pandas as pd
x = pd.DataFrame([[1,2,3],[1,2,3]], columns=["A","B","C"])
a = x.loc[0,:]
b = x.loc[1,:]
c = pd.DataFrame.from_records([a, b])
print(c)
#    A  B  C
# 0  1  2  3
# 1  1  2  3
Related