繁体   English   中英

将所有行更改为与第一行具有相同的数据,但一列除外

[英]Changing all rows to have same data as first except for one column

我有一个名为df的 dataframe ,如下所示:

x1  x2  x3  x4  x5  x6  x7  x8
1   0   5   6   10  11  56  7
67  10  4   87  2   34  22  12
44  16  9   9   5   11  56  7
99  82  10  6   87  9   5   8
5   54  66  7   36  3   2   7

我想将每一行更改为第 1 行,但 x1 列除外。

我预期的 output 将是:

x1  x2  x3  x4  x5  x6  x7  x8
1   0   5   6   10  11  56  7
67  0   5   6   10  11  56  7
44  0   5   6   10  11  56  7
99  0   5   6   10  11  56  7
5   0   5   6   10  11  56  7

我怎么能在 pandas 中做到这一点?

df.loc[:, "x2":] = df.loc[0, "x2":].values
print(df)

印刷:

   x1  x2  x3  x4  x5  x6  x7  x8
0   1   0   5   6  10  11  56   7
1  67   0   5   6  10  11  56   7
2  44   0   5   6  10  11  56   7
3  99   0   5   6  10  11  56   7
4   5   0   5   6  10  11  56   7

编辑:对于列x4

x4 = df["x4"].copy()
df.loc[:, :] = df.loc[0, :].values
df["x4"] = x4
print(df)

印刷:

   x1  x2  x3  x4  x5  x6  x7  x8
0   1   0   5   6  10  11  56   7
1   1   0   5  87  10  11  56   7
2   1   0   5   9  10  11  56   7
3   1   0   5   6  10  11  56   7
4   1   0   5   7  10  11  56   7
df.iloc[1:,1:]=np.nan#slice rows and columns to eliminate the first row and column and make them nan
df=df.ffill().astype(int)#forward fill the slice
print(df)

    x1  x2  x3  x4  x5  x6  x7  x8
0   1   0   5   6  10  11  56   7
1  67   0   5   6  10  11  56   7
2  44   0   5   6  10  11  56   7
3  99   0   5   6  10  11  56   7
4   5   0   5   6  10  11  56   7

使用df.assign

cols = ['x1'] #change list as required ex: cols = ['x1','x2']
out = df.assign(**df.drop(cols,1).iloc[0])

print(out)

   x1  x2  x3  x4  x5  x6  x7  x8
0   1   0   5   6  10  11  56   7
1  67   0   5   6  10  11  56   7
2  44   0   5   6  10  11  56   7
3  99   0   5   6  10  11  56   7
4   5   0   5   6  10  11  56   7

df.iloc与行范围1:分配给行0 所有在列范围1:

df.iloc[1:, 1:] = df.iloc[0, 1:]



print(df)

   x1  x2  x3  x4  x5  x6  x7  x8
0   1   0   5   6  10  11  56   7
1  67   0   5   6  10  11  56   7
2  44   0   5   6  10  11  56   7
3  99   0   5   6  10  11  56   7
4   5   0   5   6  10  11  56   7

暂无
暂无

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

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