提问人:DreamingDeveloper 提问时间:11/7/2023 更新时间:11/7/2023 访问量:50
如何在 python pandas 数据框中模仿 Excel 的“删除和左移”功能?
How can I imitate Excel's "Delete and shift left" feature in a python pandas data frame?
问:
我只是有一个简短的问题,因为我已经为此工作了一段时间。 我想知道如何模仿 Excel 的删除和左移,例如在 python 数据帧中。假设我想在Excel中从单元格A1删除到G8:我会突出显示单元格,右键单击并删除,然后选择左移选项。
在python中,我试图通过以下方式模仿它:
for x in range(0,6):
df.iloc[0:8,x] = df.iloc[0:8,x+6]
df.iloc[0:8,x+6] = ''
for x in range(6,len(df.columns) - 6):
df.iloc[0:8,x] = df.iloc[0:8,x+6]
df.iloc[0:8,x+6] = ''
Where essentially I will take all the rows in the first column, and replace it with all the rows in column G, and repeat for every column after. After the first "shift" is done, in the second loop, I "shift" the entire dataframe (remaining columns) to try and mimic the delete shift left feature of excel.
Results of above code:
Part 1 before delete shift left:
X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 X11 X12 X13 X14
0 1 1 1 1 1 1 1 1 3 3 3 3 3 3
1 2 2 2 2 2 2 2 2 4 4 4 4 4 4
2 3 3 3 3 3 3 3 3 5 5 5 5 5 5
3 4 4 4 4 4 4 4 4 6 6 6 6 6 6
4 6 6 6 6 6 6 6 6 20 20 20 20 20 20
5 7 7 7 7 7 7 7 7 30 30 30 30 30 30
6 8 8 8 8 8 8 8 8 40 40 40 40 40 40
7 9 9 9 9 9 9 9 9 50 50 50 50 50 50
Part 2 after delete shift left:
X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 X11 X12 X13 X14
0 1 1 3 3 3 3 3 3
1 2 2 4 4 4 4 4 4
2 3 3 5 5 5 5 5 5
3 4 4 6 6 6 6 6 6
4 6 6 20 20 20 20 20 20
5 7 7 30 30 30 30 30 30
6 8 8 40 40 40 40 40 40
7 9 9 50 50 50 50 50 50
However, I'm not sure if I am doing this correctly or if I will approach any logical errors with this method. I am sort of just improvising as I go and this is what I came up with. I imagine there's a much more elegant and efficient way of doing it. Any help is much appreciated. Thanks!
答:
0赞
Kirill Kondratenko
11/7/2023
#1
试试这个:
import pandas as pd
df = pd.DataFrame({'X1': [1, 2, 3, 4, 6, 7, 8, 9],
'X2': [1, 2, 3, 4, 6, 7, 8, 9],
'X3': [1, 2, 3, 4, 6, 7, 8, 9],
'X4': [1, 2, 3, 4, 6, 7, 8, 9],
'X5': [1, 2, 3, 4, 6, 7, 8, 9],
'X6': [1, 2, 3, 4, 6, 7, 8, 9],
'X7': [1, 2, 3, 4, 6, 7, 8, 9],
'X8': [1, 2, 3, 4, 6, 7, 8, 9],
'X9': [3, 4, 5, 6, 20, 30, 40, 50],
'X10': [3, 4, 5, 6, 20, 30, 40, 50],
'X11': [3, 4, 5, 6, 20, 30, 40, 50],
'X12': [3, 4, 5, 6, 20, 30, 40, 50],
'X13': [3, 4, 5, 6, 20, 30, 40, 50],
'X14': [3, 4, 5, 6, 20, 30, 40, 50]})
# How many columns you want to delete
delete_columns = 6
df = df[df.columns[delete_columns:]].set_axis(df.columns[:len(df.columns[delete_columns:])], axis=1)
print(df)
输出:
X1 X2 X3 X4 X5 X6 X7 X8
0 1 1 3 3 3 3 3 3
1 2 2 4 4 4 4 4 4
2 3 3 5 5 5 5 5 5
3 4 4 6 6 6 6 6 6
4 6 6 20 20 20 20 20 20
5 7 7 30 30 30 30 30 30
6 8 8 40 40 40 40 40 40
7 9 9 50 50 50 50 50 50
评论