我有一個資料框,其列如下所示:
df:
symbol json_list date
0 A [{name:S&P500, perc:25, ticker:SPY, weight:1}] 2022-01-01
1 B [{name:S&P500, perc:25, ticker:SPY, weight:0.5... 2022-01-02
2 C [{name:S&P500, perc:25, ticker:SPY, weight:1}] 2022-01-02
請注意,該json_list列包含字典串列。
我想要做的是將 DataFrame 分成兩個 DataFrame。df1包含串列中json_list只有一項df2的行和串列中json_list只有兩項或更多項的行。
因此,兩個 DataFrame 看起來像這樣:
df1:
symbol json_list date
0 A [{name:S&P500, perc:25, ticker:SPY, weight:1}] 2022-01-01
1 C [{name:S&P500, perc:25, ticker:SPY, weight:1}] 2022-01-02
df2:
symbol json_list date
0 B [{name:S&P500, perc:25, ticker:SPY, weight:0.5... 2022-01-02
有沒有一種 Pythonic 的方法來做到這一點?
先感謝您。
uj5u.com熱心網友回復:
你可以試試
cond = df.json_list.str.contains('}, {')
df1 = df[~cond]
df2 = df[cond]
uj5u.com熱心網友回復:
您可以嘗試計算列中的{計數json_list
c = df['json_list'].str.count('{')
df1 = df[c.eq(1)]
df2 = df[c.eq(2)]
print(df1)
symbol json_list date
0 A [{name:S&P500, perc:25, ticker:SPY, weight:1}] 2022-01-01
2 C [{name:S&P500, perc:25, ticker:SPY, weight:1}] 2022-01-02
print(df2)
symbol json_list date
1 B [{name:S&P500, perc:25, ticker:SPY, weight:0.5... 2022-01-02
uj5u.com熱心網友回復:
您的 JSON 列存在問題,因為字串周圍沒有引號。
假設您有一個格式正確的 JSON 物件存盤為字串,您應該能夠使用 json.JSONDecoder.decode 對其進行解碼
在目前的格式中,您只需執行以下操作即可獲得一種不太優雅的方法
df1=df[df['json_list'].apply(lambda s: s.count('{')) == 1]
df2=df.drop(df1.index)
uj5u.com熱心網友回復:
您有幾個選項,它們都通過計算大括號的出現次數。使用或使用正則str.count運算式:str.splitre.findall
# use the str.split method, looking for the closing curly bracket (or the opening bracket). Since it is a split, it will return always one element more than there are (it is not counting the occurrences)
num_json = df['json_list'].apply(lambda x: len(x.split('}')) -1)
# use re.findall to look for the bracket. This will return the the number of occurrences directly
num_json = df['json_list'].apply(lambda x: len(re.findall('\}', x)))
# count the curly brackets directly
num_json = df['json_list'].apply(lambda x: x.count('}'))
df1 = df[num_json == 1]
df2 = df[num_json > 1]
最后,您可以根據您的計數對表格進行切片
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/478274.html
上一篇:將串列的元組轉換為串列
下一篇:從文本檔案創建字典串列
