简体   繁体   English

如何在 DataFrame 中创建新列并将 select 数据从第一列移动到新列

[英]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.我的 dataframe 是 860x1,我想创建一个新列,将数据从第一列转移到第二列。

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?如何使用 pandas 将名称移动到新列?

Use slice indexing to grab every second row with either 0 or 1 as the offset from the start:使用切片索引以 0 或 1 作为从开始的偏移量获取每隔一行:

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我的代码时间: 1.81 ms ± 480
  2. BENY's code time: 2.66 ms ± 741 µs BENY 的编码时间: 2.66 ms ± 741 µs
  3. creanion's code time: 1.99 ms ± 578 µs creanion 的编码时间: 1.99 ms ± 578 µs

run on data with 10,000 rows运行 10,000 行的数据

Let us try groupby让我们试试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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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