按列拆分熊猫数据框,然后追加

时间:2020-04-26 15:01:49

标签: python pandas dataframe

我有数据框:

enter image description here

我想保留前三列,然后将它们堆叠在接下来的3个列上,这样我的数据帧的末尾只有["userID", "tweetID", "time"]

3 个答案:

答案 0 :(得分:1)

df_top = tree_df[['userID_start', 'tweetID_start', 'time_start']]
df_top.columns = ['userID', 'tweetID', 'time']
df_bottom = tree_df[['userID_end', 'tweetID_end', 'time_end']]
df_bottom.columns = ['userID', 'tweetID', 'time']
final_df = pd.concat([df_top, df_bottom])

这有效。

答案 1 :(得分:0)

似乎您需要pd.wide_to_long

df.columns=df.columns.str.split('_').map(lambda x : '_'.join(x[::-1]))
s=pd.wide_to_long(df.reset_index(),['end','start'],i='index',j='drop',sep='_',suffix='\w+').stack().unstack(-2)

答案 2 :(得分:0)

start_cols = [c for c in df.columns if c.endswith('_start')]
end_cols = [c for c in df.columns if c.endswith('_end')]

def rename(x): return x.split('_')[0]

output_df = pd.concat([
    df[start_cols].rename(columns=rename), 
    df[end_cols].rename(columns=rename)
])

您可以将开始和结束列分为两个数据框,然后pd.concat一起堆叠。