如何将pandas系列转换为 Dataframe

sbtkgmzw  于 2023-04-19  发布在  其他
关注(0)|答案(1)|浏览(174)

我有一个数据集,看起来像这样:日期说明借方贷方余额
基本上是一个系列。

def clean_data(s):
    if "Rent Due" in s:
        print("Rent Due")
        s = s.split("Rent Due")
    elif "Payment Received from Berns & Co" in s:
        print("Berns")
        s = s.split("Payment Received from Berns & Co", )
    elif "Payment" in s:
        s = s.split("Payment")
        print("Payment")
    elif "Electricity Charges" in s:
        s = s.split("Electricity Charges")
    print(s)
    return s
bv = data.apply(clean_data)

但是我不知道如何使用apply中的split函数将数据转换为列。
第一行应该是列名
但我可以使用以下命令:
bv.columns = ['DATE',' DESCRIPTION','DEBIT','CREDIT']
有人能帮忙吗?

nuypyhwy

nuypyhwy1#

使用带有n参数的Series.str.splitSeries.str.rsplit

#create one column DataFrame and remove first row
df = data.to_frame('data').iloc[1:]

df[['DATE','new']] = df['data'].str.split(n=1, expand=True)
df[['DECRIPTION','CREDIT','col','BALANCE']] = df.pop('new').str.rsplit(n=3, expand=True)

print (df)
                                                data        DATE  \
1          28/04/2022 Rent Due 1,150.00 £ -£1,150.00  28/04/2022   
2  17/05/2022 Payment Received from Berns & Co 1,...  17/05/2022   
3            27/05/2022 Payment 1,150.00 £ £1,150.00  27/05/2022   
4               28/05/2022 Rent Due 1,150.00 £ £0.00  28/05/2022   

                         DECRIPTION    CREDIT col     BALANCE  
1                          Rent Due  1,150.00   £  -£1,150.00  
2  Payment Received from Berns & Co  1,150.00   £  -£1,150.00  
3                           Payment  1,150.00   £   £1,150.00  
4                          Rent Due  1,150.00   £       £0.00

相关问题