简体   繁体   English

合并单个 pandas 数据框中的两列

[英]Merging two columns in a single pandas data frame

I have the following data frame:我有以下数据框:

df = pd.DataFrame({'id': [0.1, 0.2, 0.3, 0.4],'A': [1,2, np.NaN, np.NaN], 'A1': [np.NaN, np.NaN, 3,4]})

I'm looking to merge A1 into A (drop A1) that should result into:我希望将 A1 合并到 A(删除 A1)中,结果应该是:

df = pd.DataFrame({'id': [0.1, 0.2, 0.3, 0.4, 0.1, 0.2, 0.3, 0.4],'A': [1,2, np.NaN, np.NaN, np.NaN, np.NaN, 3,4]})

Appreciate any help.感谢任何帮助。

You can concat the two columns:您可以concat两列:

pd.concat([df[['id', 'A']], df[['id', 'A1']].rename(columns={'A1': 'A'})],
          ignore_index=True)

Or melt and rename / drop :或者melt rename / drop

df.melt('id').rename({'value': 'A'}).drop(columns='variable')

output: output:

    id    A
0  0.1  1.0
1  0.2  2.0
2  0.3  NaN
3  0.4  NaN
4  0.1  NaN
5  0.2  NaN
6  0.3  3.0
7  0.4  4.0

one option is with pivot_longer from pyjanitor ;一种选择是使用pyjanitorpivot_longer the columns have a pattern, they both start with A , we can use that to our advantage in the reshaping:列有一个模式,它们都以A开头,我们可以在重塑中利用它来发挥我们的优势:

# pip install pyjanitor
import janitor
import pandas as pd
df.pivot_longer('id', names_to = 'A', names_pattern=['A'])

    id    A
0  0.1  1.0
1  0.2  2.0
2  0.3  NaN
3  0.4  NaN
4  0.1  NaN
5  0.2  NaN
6  0.3  3.0
7  0.4  4.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM