pandas 基于 Dataframe 中的列进行匹配

bihw5rsg  于 2023-01-19  发布在  其他
关注(0)|答案(1)|浏览(136)

API的回复:-

response = [{'account_type': 'CHECKING', 'Account_Number': '9136','report_Length': 91, }, {'account_type': 'CREDITCARD', 'Account_Number': 'XXXX-XXXX-XXXX-3708', 'report_Length': 72}]
dict = {'Id': '148015388', 'total': 2964.86,'Account_Number': '9136'}
df = pd.DataFrame([dict])
df['response'] = str(response)
Expected Output:- df['report_Length'] = 91

尝试通过匹配df ['response ']中的Account_Number列和Account_Number变量来创建report_Length列。

def extractionRL(a):
    b=[]
    c= []
    d = []
    for i in a:
        b.append(i['report_Length'])
        c.append(i['account_type'])
        d.append(i['Account_Number'])
    df = pd.DataFrame()
    df['rl'] = b
    df['at'] = c
    df['Account_Number'] = d
    return df.to_dict(orient="records")
    
extractionRL(response) = [{'rl': 91, 'at': 'CHECKING', 'Account_Number': '9136'}, {'rl': 72, 'at': 'CREDITCARD', 'Account_Number': 'XXXX-XXXX-XXXX-3708'}]
yhqotfr8

yhqotfr81#

如果你正在寻找创建报告长度列。这个简单的函数将完成这一点。否则,使您的问题足够清楚,包括您的预期输出。

import pandas as pd

response = [{'account_type': 'CHECKING', 'Account_Number': '9136','report_Length': 91, }, {'account_type': 'CREDITCARD', 'Account_Number': 'XXXX-XXXX-XXXX-3708', 'report_Length': 72}]

def extractionRL(a):
    df = pd.DataFrame(a)
    df['rl'] = df['report_Length']
    df['at'] = df['account_type']
    df = df[['rl', 'at', 'Account_Number']]
    return df.to_dict(orient="records")
    
new_dicts = extractionRL(response)
print(new_dicts)

df = pd.DataFrame(new_dicts)
print(df)
[{'rl': 91, 'at': 'CHECKING', 'Account_Number': '9136'}, {'rl': 72, 'at': 'CREDITCARD', 'Account_Number': 'XXXX-XXXX-XXXX-3708'}]

   rl          at       Account_Number
0  91    CHECKING                 9136
1  72  CREDITCARD  XXXX-XXXX-XXXX-3708

相关问题