Python 将dataframe的两列的值合并为一列

Python 将dataframe的两列的值合并为一列,python,pandas,Python,Pandas,嗨,我想把两个列值附加到一个列中,如下图所示。 有人能帮我吗 | t1 | t2 | v1 | v2 | |------|------|----|----| | 0.0 | 10 | 1 | -1 | | 0.42 | 0.78 | 1 | -1 | 新数据帧 pd.wide_至_long应适用于: df['value'] = list(range(0,2)) pd.wide_to_long(df, stubnames=['t', 'v'], i='value', j='dr

嗨,我想把两个列值附加到一个列中,如下图所示。 有人能帮我吗

| t1   | t2   | v1 | v2 |
|------|------|----|----|
| 0.0  | 10   | 1  | -1 |
| 0.42 | 0.78 | 1  | -1 |
新数据帧


pd.wide_至_long应适用于:

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

pd.wide_至_long应适用于:

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

我想你要找的词是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)
输出:

t
0.00     1
0.42     1
10.00   -1
0.78    -1
Name: v, dtype: int64
0.00     1
0.42     1
10.00   -1
0.78    -1
dtype: int64
事实证明,在串联序列时,不需要匹配索引和列名。因此,这将在有n组一致命名的列的设置中实现结果:

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

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

唯一的区别是生成的序列未命名。

我认为您要查找的单词是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)
输出:

t
0.00     1
0.42     1
10.00   -1
0.78    -1
Name: v, dtype: int64
0.00     1
0.42     1
10.00   -1
0.78    -1
dtype: int64
事实证明,在串联序列时,不需要匹配索引和列名。因此,这将在有n组一致命名的列的设置中实现结果:

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

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

唯一的区别是生成的序列未命名。

如果要查找一个线性序列,则

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

如果你要找一艘班轮的话

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

塔伦,如果有人解决了你的问题,请检查:欢迎来到stackoverflow塔伦,如果有人解决了你的问题,请检查:欢迎来到stackoverflow