gpt4 book ai didi

python - 如果满足条件,则添加空行 Pandas

转载 作者:行者123 更新时间:2023-12-04 11:01:56 28 4
gpt4 key购买 nike

所以我有一个看起来像这样的数据框。每次描述为空时,有没有办法在上面添加空行?这是它的样子:

   Type     Date            Src       Description                    ST or OT
2 A 2019-06-10 AP
3 A 2019-06-10 AP Boston-Alliant Insurance Services ST
5 B 2019-05-16 AP
6 B 2019-05-16 AP City of Cambridge ST
7 B 2019-05-16 AP City of Cambridge OT
8 B 2019-08-20 AP Jeffrey Soderquist OT
905 C 2019-05-01 PR
906 C 2019-05-01 AP Citibusiness Card ST
907 C 2019-07-26 AP Pro Tool and Supply Inc OT
908 D 2019-09-25 PR
909 D 2019-09-25 PR 21/O'Leary ST
910 D 2019-09-26 PR 21/O'Leary ST

这就是我最后想要的:
   Type     Date            Src       Description                    ST or OT
2 A 2019-06-10 AP
3 A 2019-06-10 AP Boston-Alliant Insurance Services ST
5
6
7 B 2019-05-16 AP
8 B 2019-05-16 AP City of Cambridge ST
9 B 2019-05-16 AP City of Cambridge OT
10 B 2019-08-20 AP Jeffrey Soderquist OT
905
906
907 C 2019-05-01 PR
908 C 2019-05-01 AP Citibusiness Card ST
909 C 2019-07-26 AP Pro Tool and Supply Inc OT
910
911
912 D 2019-09-25 PR
913 D 2019-09-25 PR 21/O'Leary ST
914 D 2019-09-26 PR 21/O'Leary ST

最佳答案

你可以利用 np.insert它允许您通过索引位置添加值,这在使用列表时非常灵活。

indices = df.loc[df['Description'] == ' '].index.tolist() # get your blank rows.
rows_ = dict.fromkeys(df.columns.tolist(),'') # create an empty df based on your cols.

然后我们只需将rows_变量中的值分配为值,并将键分配为您选择的索引位置的列。
df_new = pd.DataFrame(np.insert(df.values, [x -1 for x in indices],
values=list(rows_.values()),
axis=0),columns=rows_.keys())
print(df_new)


Type Date Src Description ST or OT
0 A 10/06/2019 AP ST
1
2 A 10/06/2019 AP Boston-Alliant Insurance Services
3 B 16/05/2019 AP ST
4 B 16/05/2019 AP City of Cambridge OT
5 B 16/05/2019 AP City of Cambridge
6
7 B 20/08/2019 AP Jeffrey Soderquist OT
8 C 01/05/2019 PR
9 C 01/05/2019 AP Citibusiness Card ST
10
11 C 26/07/2019 AP Pro Tool and Supply Inc OT
12 D 25/09/2019 PR
13 D 25/09/2019 PR 21/O'Leary ST
14
15 D 26/09/2019 PR 21/O'Leary ST

关于python - 如果满足条件,则添加空行 Pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58755156/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com