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?
CodePudding user response:
Use slice indexing to grab every second row with either no or 1 as the offset from the start:
df = pd.DataFrame()
df['Lyrics'] = lyrics.iloc[1::2].reset_index()
df['Title'] = lyrics.iloc[0::2].reset_index()
CodePudding user response:
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
CodePudding user response:
pd.DataFrame(df.to_numpy().reshape(-1,2))[[1,0]].rename(columns={1:"Lyrics", 0:"Title"})
a fun point:)
- my code time:
1.81 ms ± 480
- BENY's code time:
2.66 ms ± 741 µs
- creanion's code time:
1.99 ms ± 578 µs
run on data with 10,000 rows