【问题标题】:Is there a way to append values of the column with same column name using python?有没有办法使用 python 附加具有相同列名的列的值?
【发布时间】:2019-06-07 06:26:23
【问题描述】:

我有一个数据集,其中一些列具有相同的列名。我想合并具有相同列名的列,以便将值作为行附加。并且,对于没有具有相同列名的列的列,在行中附加 0。

我试过融化,但它似乎不适用于我需要的格式。

样本数据:

print (df)
       Date  Column_A  Column_A  Column_B
0  1/2/2018         3         2         3
1  2/2/2018         4         7         1
2  3/2/2018         2         2         6
3  4/2/2018         1         1         4    

预期输出:

       Date  Column_A  Column_B
0  1/2/2018         3       3.0
1  2/2/2018         4       1.0
2  3/2/2018         2       6.0
3  4/2/2018         1       4.0
4  1/2/2018         2       0.0
5  2/2/2018         7       0.0
6  3/2/2018         2       0.0
7  4/2/2018         1       0.0

【问题讨论】:

  • 哎呀,似乎 dupe 被错误地关闭了,但 100% 肯定,print (df.columns) 是什么?有重复的列名?
  • 是的,只是列名相同,而不是其中的值。@jezrael

标签: python pandas dataframe timestamp data-processing


【解决方案1】:

想法是在具有GroupBy.cumcount 的列中创建MultiIndex,然后通过DataFrame.stack 重塑,通过DataFrame.sort_index 按MultiIndex 的第二级排序,最后通过将第一级转换为Date 列通过double @ 删除第二级987654324@:

df = df.set_index('Date')
s = df.columns.to_series()

df.columns = [df.columns, s.groupby(s).cumcount()]
df = df.stack().sort_index(level=1).fillna(0).reset_index(level=1, drop=True).reset_index()
print (df)
       Date  Column_A  Column_B
0  1/2/2018         3       3.0
1  2/2/2018         4       1.0
2  3/2/2018         2       6.0
3  4/2/2018         1       4.0
4  1/2/2018         2       0.0
5  2/2/2018         7       0.0
6  3/2/2018         2       0.0
7  4/2/2018         1       0.0

【讨论】:

    猜你喜欢
    • 2019-05-12
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-25
    • 2020-07-12
    • 1970-01-01
    相关资源
    最近更新 更多