合并具有相似名称的数据框列。并连接以“,”(逗号)分隔的值

时间:2021-06-09 14:58:13

标签: python pandas dataframe pandas-groupby string-operations

input file contains the product and its price on a particular date

product  05-Oct-2020  07-Oct-2020 09-Nov-2020 13-Nov-2020
A        66.2         69.5        72.95       76.55
B        368.7        382.8       384.7       386.8

output file should, combine all the days of month in one column and concatenate values with separated with comma (,)

product   Oct-2020         Nov-2020
A         66.2, 69.5       72.95, 76.55
B         368.7, 382.8     384.7, 386.8

我尝试将列名更改为日期格式,从“1-jan-2020”更改为“jan-2020” 与

keys = [dt.strptime(key, "%d-%b-%Y").strftime("%B-%Y") for key in data.keys()]

在df转置之后我们可以使用groupby。

就像有选项可以分组并将值相加为:-

df.groupby().sum()

有什么东西可以连接值(字符串操作)并用逗号分隔它们。

click here to get sample data

感谢任何方向。

1 个答案:

答案 0 :(得分:0)

诀窍是在列上使用 Grouper

inp = pd.read_excel("Stackoverflow sample.xlsx")

df = inp.set_index("Product")
df.columns = pd.to_datetime(df.columns)

out = (
    df
    .T
    .groupby(pd.Grouper(level=0, freq="MS"))
    .agg(lambda xs: ", ".join(map(str, filter(pd.notnull, xs))))
    .T
)

使用提供的示例,这会为 out 生成以下 5 行: enter image description here

如果要转换为特定日期格式,请执行

out.columns = out.columns.strftime("%b-%Y")

导致 enter image description here

相关问题