我的数据框形状如下:
A B C D E
213-1 XL NaN NaN NaN
21 22.0 12 232.0 101.32
23-0 L NaN NaN NaN
12 23 12 232.2 NaN
31-0 LS NaN NaN NaN
70 70 23 NaN 21.22
我想将该数据框的第二行移动到上面的行,以便只剩下合并行,如预期结果所示:
ID Name A B C D E
213-1 XL 21 22.0 12 232.0 101.32
23-0 L 12 23 12 232.2 NaN
31-0 LS 70 70 23 NaN 21.22
有可能和熊猫有关吗?
答案 0 :(得分:5)
我会使用concat
:
new_df = pd.concat((df.iloc[::2, :2].reset_index(drop=True),
df.iloc[1::2].reset_index(drop=True)),
axis=1)
# rename
new_df.columns = ['ID', 'Name'] + new_df.columns[2:].to_list()
输出:
ID Name A B C D E
0 213-1 XL 21 22.0 12.0 232.0 101.32
1 23-0 L 12 23 12.0 232.2 NaN
2 31-0 LS 70 70 23.0 NaN 21.22
答案 1 :(得分:2)
concat
在df.iloc[::2]
和df.iloc[1::2]
上:
df1= (df.iloc[::2].dropna(axis=1).reset_index(drop=True))
df2 = (df.iloc[1::2].reset_index(drop=True))
print (pd.concat([df1,df2],ignore_index=True,axis=1))
#
0 1 2 3 4 5 6
0 213-1 XL 21 22.0 12.0 232.0 101.32
1 23-0 L 12 23 12.0 232.2 NaN
2 31-0 LS 70 70 23.0 NaN 21.22
答案 2 :(得分:0)
master_df = df[~df['C'].isna()].reset_index(drop=True)
master_df[['ID','Name']] = pd.DataFrame(df[df['C'].isna()][['A','B']].reset_index(drop=True), index=master_df.index)
输出
##print(master_df[['ID','Name','A', 'B', 'C', 'D', 'E']])
ID Name A B C D E
0 213-1 XL 21 22.0 12.0 232.0 101.32
1 23-0 L 12 23 12.0 232.2 NaN
2 31-0 LS 70 70 23.0 NaN 21.22