在 Pandas 数据框中将第二行移到上方一行 - python

我有这种形状的数据框:

    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

熊猫有可能吗?

参考方案

我会使用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

在 Pandas 中放置多列 - python

我正在尝试使用以下代码在熊猫数据框中按索引号删除多列(数据集中的第2列和第70列,分别索引为1和69):df.drop([df.columns[[1, 69]]], axis=1, inplace=True) 我收到以下错误:TypeError: unhashable type: 'Index' 在我的代码中,[1,69]突出显示并说:E…

在 Pandas df中找到timedelta对象的均值和标准差 - python

我想通过银行与下面显示的两列mean来计算standard deviation的timedelta和dataframe。当我运行代码(也显示在下面)时,出现以下错误:pandas.core.base.DataError: No numeric types to aggregate 我的数据框: bank diff Bank of Japan 0 days 0…

在 Pandas 图中仅隐藏轴标签,而不是整个轴 - python

我可以使用以下命令清除Pandas图中xlabel的文本:plt.xlabel("") 而是可以隐藏标签吗?可能类似于.xaxis.label.set_visible(False)。 参考方案 From the Pandas docs- Series和DataFrame上的plot方法只是对plt.plot()的简单包装:这意味着您可以使…

在 Pandas 中使用带有MultiIndex的.loc? - python

有谁知道是否可以使用DataFrame.loc方法从MultiIndex中进行选择?我有以下DataFrame,并希望能够访问('at', 1),('at', 3),('at', 5)等等的索引(非顺序)位于“Dwell”列中的值。我很希望能够执行类似data.loc[['at'…

python :安装 python 后,如何导入 Pandas - python

我已经安装了 python 。现在,当我尝试跑步时import pandas as pd 我收到以下错误Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> import pandasFile ImportError: …