[英]How do I merge multiple columns with similar names in a Pandas Dataframe without losing data
[英]How can I turn a pandas dataframe with columns with similar names into rows?
# 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.