繁体   English   中英

如何将具有相似名称的列的 pandas dataframe 转换为行?

[英]How can I turn a pandas dataframe with columns with similar names into rows?

例如,我有下面的 dataframe 在此处输入图像描述

我想变成这样的东西:

Timetsamp     | invoice_number | invoice_amount

10/14/2019    |   20565116     |  101.09

10/14/2019    |   20617023     |  505.57

10/15/2019    |   20600496     |  503.2

10/15/2019    |   20582306     |  501.11
# timestamp dataframe
timestamp = df[['Timestamp']]

# stores the new dataframe with timestamp and invoices
new_df = pd.DataFrame():

# iterate through the cols in original dataframe in steps of 2
for c in range(1,len(df.columns),2):

    # get the column invoice number and amount
    temp = df[[df.columns[c],df.columns[c+1]]
    # concat with the timestamp
    temp = pd.concat([timestamp, temp], axis = 1)
    # make a bigger dataframe
    new_df = pd.concat([new_df, temp], axis = 0, ignore_index = True)

像这样的东西会起作用:

group = df.set_index('timestamp').T.groupby(df.columns[1:])
df = pd.concat([grp.T.stack().droplevel(1).rename(idx).to_frame() for idx, grp in group], 1)

暂无
暂无

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

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