python-3.x 从数据框中获取账户名称、卡和总金额

lhcgjxsq  于 2022-12-24  发布在  Python
关注(0)|答案(1)|浏览(138)
Account / Card  Balance Start  Balance End  Difference
0            MASTER         701.00       701.00        0.00
0               NaN            NaN          NaN         NaN
1   Algemeen/*!%@!#        2240.25      2181.45      -58.80
9         120989894           0.00         0.00        0.00
5         159142752           0.00         0.00        0.00
4         286695535         300.00       300.00        0.00
12        578951057          30.00        30.00        0.00
13        706602827           0.00         0.00        0.00
2         735592139           0.00         0.00        0.00
11        810226753         250.00       229.16      -20.84
3         811695012           0.00         0.00        0.00
6         818329167          22.85        22.85        0.00
0               NaN            NaN          NaN         NaN
2           General        3913.56      3813.56     -100.00
8         138738399          42.79        27.79      -15.00
0         646746507           0.00         0.00        0.00
1         767402418           2.90         2.90        0.00
10        948214665         545.07       391.57     -153.50
7         A98744534         461.32        75.36     -385.96
0               NaN            NaN          NaN         NaN
0            Totals        8509.74      7775.64     -734.10

我想在单独的列中获取帐户名和卡。例如“Master”、“Algemeen/*!%@!#"、“GENERAL”。我尝试使用groupby获取,但这对我不起作用。

for date, new_df in balances.groupby(level=0):
    print(new_df)
oknrviil

oknrviil1#

我为这个问题写了一些代码,但是如果您也定义预期输出的话就更好了(我使用apply函数来检查每个值的长度是否为9)

import pandas as pd

df = pd.read_csv('./stackoverflowacctcard.csv')
def collect_card(acct_card):
    if len(str(acct_card)) != 9:
        return acct_card
    else:
        return ''
def collect_account(acct_card):
    if len(str(acct_card)) == 9:
        return acct_card
    else:
        ''
df['Card'] = df['Account / Card'].apply(collect_card)
df['Account'] = df['Account / Card'].apply(collect_account)
df.drop('Account / Card', axis=1, inplace=True)
df

相关问题