python - 将不同的列值堆叠到 Pandas 数据框中的一列中

标签 python pandas dataframe multiple-columns melt

我有以下数据框-

df = pd.DataFrame({
    'ID': [1, 2, 2, 3, 3, 3, 4],
    'Prior': ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
    'Current': ['a1', 'c', 'c1', 'e', 'f', 'f1', 'g1'],
    'Date': ['1/1/2019', '5/1/2019', '10/2/2019', '15/3/2019', '6/5/2019',
             '7/9/2019', '16/11/2019']
})

这是我想要的输出-

desired_df = pd.DataFrame({
    'ID': [1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4],
    'Prior_Current': ['a', 'a1', 'b', 'c', 'c1', 'd', 'e', 'f', 'f1', 'g',
                      'g1'],
    'Start_Date': ['', '1/1/2019', '', '5/1/2019', '10/2/2019', '', '15/3/2019',
                   '6/5/2019', '7/9/2019', '', '16/11/2019'],
    'End_Date': ['1/1/2019', '', '5/1/2019', '10/2/2019', '', '15/3/2019',
                 '6/5/2019', '7/9/2019', '', '16/11/2019', '']
})

我尝试了以下 -

keys = ['Prior', 'Current']
df2 = (
    pd.melt(df, id_vars='ID', value_vars=keys, value_name='Prior_Current')
        .merge(df[['ID', 'Date']], how='left', on='ID')
)
df2['Start_Date'] = np.where(df2['variable'] == 'Prior', df2['Date'], '')
df2['End_Date'] = np.where(df2['variable'] == 'Current', df2['Date'], '')
df2.sort_values(['ID'], ascending=True, inplace=True)

但这似乎不起作用。请帮忙。

最佳答案

你可以使用堆栈pivot_table:

k = df.set_index(['ID', 'Date']).stack().reset_index()
df = k.pivot_table(index = ['ID',0], columns = 'level_2', values = 'Date', aggfunc = ''.join, fill_value= '').reset_index()
df.columns = ['ID', 'prior-current', 'start-date', 'end-date']

输出:

    ID prior-current  start-date    end-date
0    1             a                1/1/2019
1    1            a1    1/1/2019            
2    2             b                5/1/2019
3    2             c    5/1/2019   10/2/2019
4    2            c1   10/2/2019            
5    3             d               15/3/2019
6    3             e   15/3/2019    6/5/2019
7    3             f    6/5/2019    7/9/2019
8    3            f1    7/9/2019            
9    4             g              16/11/2019
10   4            g1  16/11/2019            

说明:

stack/reset_index 之后 df 将如下所示:

   ID        Date  level_2   0
0    1    1/1/2019    Prior   a
1    1    1/1/2019  Current  a1
2    2    5/1/2019    Prior   b
3    2    5/1/2019  Current   c
4    2   10/2/2019    Prior   c
5    2   10/2/2019  Current  c1
6    3   15/3/2019    Prior   d
7    3   15/3/2019  Current   e
8    3    6/5/2019    Prior   e
9    3    6/5/2019  Current   f
10   3    7/9/2019    Prior   f
11   3    7/9/2019  Current  f1
12   4  16/11/2019    Prior   g
13   4  16/11/2019  Current  g1

现在,我们可以使用 IDcolumn 0 作为索引/level_2 作为列/Date 列作为值(value)。

最后,我们需要重命名列以获得所需的结果。

关于python - 将不同的列值堆叠到 Pandas 数据框中的一列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67870622/

相关文章:

python - DataFrame 的给定列非零的行数

从源代码 : gcc. orig: 目录构建时出现 Python 2.7.6 错误:没有这样的文件或目录

python - 读取 xml 并尝试将其提取到 2 个不同的 xml 中

python - 如何获取 Python 中内置函数的参数个数?

python - 如何为每个用户 ID 重复一组日期?

python - 如何使用内连接合并两个数据框,而不产生重复的列?

python - 使用选定值作为索引的 Pandas 数据透视表

php - 如何从传入的电子邮件中获取数据,然后将数据复制到某个目录

r - 数据框 : create column by applying a function to groups of rows

python - pandas.Panel 弃用警告实际推荐的是什么?