简体   繁体   中英

Python dataframe tranpose a single value from every nth row into a new column

I have these alternating rows of times, and I want the times side by side, the Name and Value column are always redundant so the only value I am interested in preserving is the Time column by transposing those values a new column. But I can't quite figure out how to do this gracefully

Before:

Name Time Value Value2
0 Q 09:15 1
1 Q 09:16 0
2 Q 09:18 1
3 Q 09:19 0
4 P 22:30 1
5 P 23:20 0

After:

Name Time Value Value2
0 Q 09:15 1 09:16
1 Q 09:18 1 09:19
2 P 23:20 1 23:20

here is a solution that works with your example. In df1 you have the output

import pandas as pd


df=pd.DataFrame({
    "Name":["Q"  ,"Q" ,"Q" ,"Q" ,"P" ,"P"],
    "Time":["09:15", "09:16", "09:18", "09:19", "22:30", "23:20"],
    "Value":[1 ,0 ,1 ,0 ,1 ,0],
    "Value2":[None,None,None,None,None,None]})

df1=df.loc[df["Value"]!=0]
df2=df.loc[df["Value"]==0]
df2.index=df1.index
df1=df1.drop(columns=["Value2"])

df2=df2.drop(columns=["Name","Value","Value2"])
df2=df2.rename(columns={"Time":"Value2"})

df1=df1.join(df2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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