我有一个看起来像这样的df:
col1
aaa
1
bbb
2
ccc
3
Run Code Online (Sandbox Code Playgroud)
我该如何从数据框中提取第二行并使其成为自己的列,如下所示:
col1 col2
aaa 1
bbb 2
ccc 3
Run Code Online (Sandbox Code Playgroud)
我尝试了这个:
df[::1]
Run Code Online (Sandbox Code Playgroud)
由于第二行的索引为1,但是我没有返回要查找的数据。
使用 reshape
pd.DataFrame(df.col1.values.reshape(-1,2),columns=['c1','c2'])
Run Code Online (Sandbox Code Playgroud)
完整示例:
import pandas as pd
df = pd.DataFrame({
'col1': ['aaa','1','bbb','2','ccc','3']
})
df = pd.DataFrame(df.col1.values.reshape(-1,2),columns=['c1','c2'])
df.c2 = df.c2.astype(int) # optional to convert col to int
print(df)
Run Code Online (Sandbox Code Playgroud)
退货
c1 c2
0 aaa 1
1 bbb 2
2 ccc 3
Run Code Online (Sandbox Code Playgroud)