輸入資料:
data = [
['0039384', [{'A': 415}, {'A': 228}, {'B': 360}, {'B': 198}, {'C': 300}, {'C': 165}]],
['0035584', [{'A': 345}, {'A': 117}, {'B': 223}, {'B': 554}, {'C': 443}, {'C': 143}]]
]
df = pd.DataFrame(data=data, columns=['id', 'prices'])
我想得到這個結果:
id CurrentPrice_A LastPrice_C CurrentPrice_B LastPrice_B CurrentPrice_C LastPrice_C
0039384 415 228 360 198 300 165
我試圖將 dict 分開,然后將每一列進行替換和重命名而不是獲取價格,但它需要大約 10 行代碼。你知道任何簡短而快速的方法嗎?
uj5u.com熱心網友回復:
迭代資料框的每一行很方便,這樣您就可以控制演算法,將字典兩兩壓縮(以便合并當前和最后)并動態分配列名及其值。
為方便起見,您可以使用串列和臨時字典來代替 pd.concat()。
import pandas as pd
data = [
['0039384', [{'A': 415}, {'A': 228}, {'B': 360}, {'B': 198}, {'C': 300}, {'C': 165}]],
['0035584', [{'A': 345}, {'A': 117}, {'B': 223}, {'B': 554}, {'C': 443}, {'C': 143}]]
]
df = pd.DataFrame(data=data, columns=['id', 'prices'])
new_df_rows = []
for index, row in df.iterrows():
grouped_prices = zip(row.prices[::2], row.prices[1::2]) # create groups two-by-two
tmp_dict = {'id': row.id}
for curr_price, last_price in grouped_prices:
tmp_dict.update({
'CurrentPrice_' str(list(curr_price.keys())[0]): int(list(curr_price.values())[0]),
'LastPrice_' str(list(last_price.keys())[0]): int(list(last_price.values())[0])
})
new_df_rows.append(tmp_dict)
new_df = pd.DataFrame(new_df_rows)
print(new_df)
輸出將是:
id CurrentPrice_A LastPrice_A CurrentPrice_B LastPrice_B CurrentPrice_C LastPrice_C
0 0039384 415 228 360 198 300 165
1 0035584 345 117 223 554 443 143
uj5u.com熱心網友回復:
首先將串列行轉換為新列:
dfx = pd.DataFrame(df['prices'].tolist(),index=df.id)
print(dfx)
'''
0 1 2 3 4 5
id
0039384 {'A': 415} {'A': 228} {'B': 360} {'B': 198} {'C': 300} {'C': 165}
0035584 {'A': 345} {'A': 117} {'B': 223} {'B': 554} {'C': 443} {'C': 143}
'''
然后讓我們將列分成奇數和偶數。奇數代表最后價格,偶數代表當前價格:
last=list(filter(lambda x: x % 2, list(dfx.columns))) #[1, 3, 5]
currents=list(sorted(set(dfx.columns) - set(last))) #[0, 2, 4]
現在,重命名列:
for i in currents:
dfx=dfx.rename(columns={i:'CurrentPrice_{}'.format(list(dfx[i].iloc[0].keys())[0])})
for i in last:
dfx=dfx.rename(columns={i:'LastPrice_{}'.format(list(dfx[i].iloc[0].keys())[0])})
print(dfx)
'''
id CurrentPrice_A LastPrice_A CurrentPrice_B LastPrice_B CurrentPrice_C LastPrice_C
0039384 {'A': 415} {'A': 228} {'B': 360} {'B': 198} {'C': 300} {'C': 165}
0035584 {'A': 345} {'A': 117} {'B': 223} {'B': 554} {'C': 443} {'C': 143}
'''
最后,從字典中獲取值:
for i in dfx.columns:
dfx[i]=dfx[i].apply(lambda x: list(x.values())[0])
print(dfx)
'''
id CurrentPrice_A LastPrice_A CurrentPrice_B LastPrice_B CurrentPrice_C LastPrice_C
0039384 415 228 360 198 300 165
0035584 345 117 223 554 443 143
'''
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/534510.html
上一篇:根據另一個字典的鍵名創建新字典
