问题
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:
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
回答2:
If you are looking for one liner then
df[['t1', 'v1']].append(df[['t2', 'v2']].rename(columns={'t2': 't1', 'v2': 'v1'}), ignore_index=True)
回答3:
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.
来源:https://stackoverflow.com/questions/59417956/combine-values-of-two-columns-of-dataframe-into-one-column