在python中按索引组进行迭代

时间:2018-10-09 14:11:40

标签: python-3.x pandas iterator

我需要将VIN数据分组发送给api。 VIN按其前三个字母wmi分组。 wmi是数据帧索引。我正在测试中,尝试按组呼叫时无法仅打印VIN。下面的代码是我经过几个小时的工作后才尝试获取仅用于打印VIN的代码。

在我的实际代码中,我需要按WMI拉组并将这些VIN仅发送到api;然后拉下一组并将VIN仅发送到api。我的循环在某处不正确。

#Stack exchange 

import pandas as pd
#develop the data
df = pd.DataFrame(columns = ["vin"], data = ['LHJLC79U58B001633','SZC84294845693987','LFGTCKPA665700387','L8YTCKPV49Y010001',
                                             'LJ4TCBPV27Y010217','LFGTCKPM481006270','LFGTCKPM581004253','LTBPN8J00DC003107',
                                             '1A9LPEER3FC596536','1A9LREAR5FC596814','1A9LKEER2GC596611','1A9L0EAH9C596099',
                                             '22A000018'])
df['wmi'] = df['vin'].str[0:3]
df.set_index('wmi', inplace = True)

for name, group in df.groupby('wmi'):
    df1 = pd.DataFrame()
    for i in group:
        i = group.vin
        print(i)

1 个答案:

答案 0 :(得分:0)

apply用于分组数据怎么办?

def do_something(df):
    print(df)

df = pd.DataFrame(columns = ["vin"], data = ['LHJLC79U58B001633','SZC84294845693987',
                                         'LFGTCKPA665700387','L8YTCKPV49Y010001',
                                         'LJ4TCBPV27Y010217','LFGTCKPM481006270',
                                         'LFGTCKPM581004253','LTBPN8J00DC003107',
                                         '1A9LPEER3FC596536','1A9LREAR5FC596814',
                                         '1A9LKEER2GC596611','1A9L0EAH9C596099',
                                         '22A000018'])
df['wmi'] = df['vin'].str[0:3]
df.groupby('wmi').apply(do_something)

OUT:

                  vin  wmi
8   1A9LPEER3FC596536  1A9
9   1A9LREAR5FC596814  1A9
10  1A9LKEER2GC596611  1A9
11   1A9L0EAH9C596099  1A9
                  vin  wmi
8   1A9LPEER3FC596536  1A9
9   1A9LREAR5FC596814  1A9
10  1A9LKEER2GC596611  1A9
11   1A9L0EAH9C596099  1A9
          vin  wmi
12  22A000018  22A
                 vin  wmi
3  L8YTCKPV49Y010001  L8Y
                 vin  wmi
2  LFGTCKPA665700387  LFG
5  LFGTCKPM481006270  LFG
6  LFGTCKPM581004253  LFG
                 vin  wmi
0  LHJLC79U58B001633  LHJ
                 vin  wmi
4  LJ4TCBPV27Y010217  LJ4
                 vin  wmi
7  LTBPN8J00DC003107  LTB
                 vin  wmi
1  SZC84294845693987  SZC