1

hi I want to append two column values into a single column, something like shown below in pandas. Can anyone help me out in doing that?

| t1   | t2   | v1 | v2 |
|------|------|----|----|
| 0.0  | 10   | 1  | -1 |
| 0.42 | 0.78 | 1  | -1 |

new dataframe

| t1,t2 combined | v1,v2 combined |
|----------------|----------------|
| 0.0            | 1              |
| 0.42           | 1              |
| 10             | -1             |
| 0.78           | -1             |
1

3 Answers 3

4

pd.wide_to_long should work:

df['value'] = list(range(0,2))
pd.wide_to_long(df, stubnames=['t', 'v'], i='value', j='dropme', sep='').reset_index().drop(columns=['value', 'dropme'])                                                           

       t  v
0   0.00  1
1   0.42  1
2  10.00 -1
3   0.78 -1
Sign up to request clarification or add additional context in comments.

Comments

0

If you are looking for one liner then

df[['t1', 'v1']].append(df[['t2', 'v2']].rename(columns={'t2': 't1', 'v2': 'v1'}), ignore_index=True)

Comments

0

I think the word you are looking for is concatenate.

data = [ 
    [0.0, 10, 1, -1], 
    [0.42, 0.78, 1, -1]
]
df = pd.DataFrame(data, columns=['t1', 't2', 'v1', 'v2'])
v1 = df.set_index('t1')['v1'].rename('v')
v1.index.name = 't'
v2 = df.set_index('t2')['v2'].rename('v')
v2.index.name = 't'
combined = pd.concat([v1, v2])
print(combined)

Output:

t
0.00     1
0.42     1
10.00   -1
0.78    -1
Name: v, dtype: int64

Turns out you don't need to match the index and column names when concatenating series. So this achieves the result in the setting where there are n sets of consistently-named columns:

combined = pd.concat([df.set_index(f"t{i}")[f"v{i}"] for i in range(1, 3)])
print(combined)

Output:

0.00     1
0.42     1
10.00   -1
0.78    -1
dtype: int64

The only difference is the resulting series is unnamed.

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.