1

I have a dataframe like this-

                 0
0            a  43
1            b  630
2            r  587
3            i  462
4            g  153
5            t  266

I want to create a new dataframe which looks like this-

     a         b     r       i     g        t
0    43       630   587    462    153      266

3 Answers 3

2

You can transpose your dataframe via df.T or df.transpose():

df = pd.DataFrame([['A', 1], ['B', 2], ['C', 3], ['D', 4], ['E', 5]],
                  columns=['col1', 'col2'])

print(df)

  col1  col2
0    A     1
1    B     2
2    C     3
3    D     4
4    E     5

res = df.set_index('col1').T

Result:

print(res)

col1  A  B  C  D  E
col2  1  2  3  4  5
Sign up to request clarification or add additional context in comments.

2 Comments

I agree... however it's a little unclear whether the OP does actually have two columns or whether it's one column that needs processing to transpose on... I have a feeling (probably wrong) they need to split that column to get the names, then just pivot the result...
@JonClements, Hmm, I see. I just took OP's question very literally. Will update if more is required.
1

If you have just one column with this format a 43, this should work:

df.columns = ['col']
df = pd.DataFrame(df.col.str.split(' ',1).tolist(), columns = ['col1','col2']).T.reset_index(drop=True)
df = df.rename(columns=df.iloc[0]).drop(df.index[0])

Input:

df = pd.DataFrame(data=[
     ['a 43',],
     ['b 630'],
     ['r 587']],
columns=['col'])

     col
0   a 43
1  b 630
2  r 587

Output:

    a    b    r
1  43  630  587

3 Comments

my column name is 0 by default...what changes to be made?
Here df.col.str.split instead of col the name of your columns. try with df[0] or df['0']
Or even better, add this line: df.columns = ['col'] I've updated the answer
1

Create 2d array by list comprehension with split and then new Dataframe by constructor:

a = np.array([x.split() for x in df['0']])

df = pd.DataFrame([a[:, 1]], columns=a[:, 0])
print (df)
    a    b    r    i    g    t
0  43  630  587  462  153  266

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.