[英]Extract data from a pandas DataFrame in Python
這是我擁有的DataFrame的示例,我想根據每個時間范圍提取“ totalCount”的相應數據。
df = [{"username": "last",
"time_data": "{\"hours\":[{\"hour\":\"00:00\",\"postCount\":\"5\",\"topicCount\":\"3\",\"totalCount\":80},{\"hour\":\"01:00\",\"postCount\":\"11\",\"topicCount\":\"6\",\"topciCount\":31}"
},
{"username": "truk",
"time_data": "{\"hours\":[{\"hour\":\"00:00\",\"postCount\":\"11\",\"topicCount\":\"6\",\"totalCount\":362},{\"hour\":\"01:00\",\"postCount\":\"22\",\"topicCount\":\"8\",\"topicCount\":355}"
}]
df = pd.DataFrame(df)
df
我已經使用此代碼來獲取“ 00:00”和“ 01:00”的“ postCount”:
df_h0 = df.copy()
df_h0['hour']='00:00'
df_h0['totalCount']=df.time_data.str.split('"00:00","postCount":"').str[1].str.split('","topic').str[0]
df_h0 = df_h0.fillna(0)
df_h1 = df.copy()
df_h1['hour']='01:00'
df_h1['totalCount']=df.time_data.str.split('"01:00","postCount":"').str[1].str.split('","topic').str[0]
df_h1 = df_h1.fillna(0)
df_tot = df_h0.append([df_h1])
df_tot.head()
但是現在我想獲取的“ totalCount”不僅僅在小時數旁邊。 有人知道該怎么做嗎?
預期產量:
time_data username hour totalCount
0 {"hours":[{"hour":"00:00","postCount":"5","top... last 00:00 80
1 {"hours":[{"hour":"00:00","postCount":"11","to... truk 00:00 362
0 {"hours":[{"hour":"00:00","postCount":"5","top... last 01:00 31
1 {"hours":[{"hour":"00:00","postCount":"11","to... truk 01:00 355
要解決此問題,您應該制作一個正則表達式以將文本提取到正確的位置。 但這不是解決問題的正確方法。 理想情況下,為了充分利用DataFrame結構,應該將接收到的數據解析為DataFrame列,以便可以使用更方便,更高效的方法:
totals_over_one_hundred = df.loc[df['totalCount'] > 100]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.