简体   繁体   中英

How to create a new column in a DataFrame and move select data from the first column to the new column

My dataframe is 860x1 and I want create a new column that shifts data from first column to the second.

example:

      Lyrics
0.    name
1.    lyric
2.    name
3.    lyric
4.    name
5.    lyric

What I need is:

      Lyrics     Title
0.    lyric      name
1.    lyric      name
2.    lyric      name
3.    lyric      name

The odd index numbers are lyrics and even are names. How can I move the names to a new column using pandas?

Use slice indexing to grab every second row with either 0 or 1 as the offset from the start:

df = pd.DataFrame()
df['Lyrics'] = lyrics.iloc[1::2].reset_index(drop=True)
df['Title'] = lyrics.iloc[0::2].reset_index(drop=True)
pd.DataFrame(df.to_numpy().reshape(-1,2))[[1,0]].rename(columns={1:"Lyrics", 0:"Title"})

a fun point:)

  1. my code time: 1.81 ms ± 480
  2. BENY's code time: 2.66 ms ± 741 µs
  3. creanion's code time: 1.99 ms ± 578 µs

run on data with 10,000 rows

Let us try groupby

out = pd.concat([y.reset_index(drop=True) for _ , y in df.groupby(df.index%2)['Lyrics']],axis=1,keys= ['Title','Lyrics'])
Out[49]: 
  Title Lyrics
0  name  lyric
1  name  lyric
2  name  lyric

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