Reputation: 15
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?
Upvotes: 0
Views: 61
Reputation: 2753
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)
Upvotes: 1
Reputation: 2372
pd.DataFrame(df.to_numpy().reshape(-1,2))[[1,0]].rename(columns={1:"Lyrics", 0:"Title"})
a fun point:)
1.81 ms ± 480
2.66 ms ± 741 µs
1.99 ms ± 578 µs
run on data with 10,000 rows
Upvotes: 1
Reputation: 323366
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
Upvotes: 0