Python dataframe 从第 1 列中选择特定行数并从第 2 列中选择所有行

问题描述 投票:0回答:1

我的 Excel 工作表中有两列,如下所示

enter image description here

我想在 python 中迭代(如果可能的话使用数据框)来生成多个 excel 工作表,其中我的 excel 文件如下所示

File_1 输出(第 1 列将包含 10 个城市,第 2 列将包含所有人)

enter image description here

File_2 输出(第 1 列将获取接下来的 10 个城市,第 2 列将包含所有人员,没有任何变化)

enter image description here

for循环将继续迭代,直到完成所有行。 假设如果我在第 1 列中有 105 个城市,则代码将生成 11 个输出文件,其中最后一个文件在第 1 列中仅包含 5 个城市。

我尝试使用以下代码

rows_per_file = 10
n_chunks = PC // rows_per_file


for i in range(n_chunks):
    start = i*rows_per_file
    stop = (i+1) * rows_per_file
    sub_df= df(df.iloc[start:stop,0],0)
    sub_df2=df(df.iloc[0:UC,1],1)
    sub_df3= sub_df+sub_df2
    sub_df3.to_excel(f"test-{i}.xlsx", sheet_name="sheet")

但它为我提供了单列中的所有数据,并将我的第二列也切片为 10 人,而不是全部 26 人。 我尝试过不同的方法,但一直无法弄清楚。

任何帮助表示赞赏:)

enter image description here

python pandas excel
1个回答
0
投票
import pandas as pd
length = 100
df = pd.DataFrame({"City":[f"City{i}" for i in range(1,length+1)],"Person":[f"Person{i}" for i in range(1,length+1)]})

输出:

城市
城市1 人1
城市2 人2
城市3 第三人
... ...
城市100 100人
© www.soinside.com 2019 - 2024. All rights reserved.