我们如何像通常在 excel 上所做的那样在 Pandas 数据框中剪切和粘贴数据。考虑使用鼠标并进行剪切粘贴操作。在 Pandas 数据框中为单个元素和多个元素执行此操作的最简单和最简单的方法是什么?为了演示这里是一个例子。
col_1 | col_2 | col_3 | |
---|---|---|---|
一种 | d | XYZ | |
乙 | 电子 | G | |
C | F | H |
在Excel中,我可以去col_3的第一个单元格,剪切XYZ,然后将其粘贴到col_2的最后一个单元格
col_1 | col_2 | col_3 | |
---|---|---|---|
一种 | d | NaN | |
乙 | 电子 | G | |
C | XYZ | H |
在熊猫中这样的操作容易吗?我知道写几行代码是可行的。但是有没有更温和的方法来做到这一点(比如内置函数等)非常感谢
我认为不会有内置函数来做到这一点。但你可以为自己创造一个。喜欢:
def cut_and_paste(df, cut_x, cut_y, paste_x, paste_y):
if type(df.loc[cut_x, cut_y]) in [pd.DataFrame, pd.Series]:
df.loc[paste_x, paste_y] = df.loc[cut_x, cut_y].values
else:
df.loc[paste_x, paste_y] = df.loc[cut_x, cut_y]
df.loc[cut_x, cut_y] = np.nan
cut_and_paste(df, 0, 'col_3', 2, 'col_2')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句