我在撰寫回圈以在 Python 中對 Dataframe 進行子集化時遇到問題。
這是我關于堆疊溢位的第一篇文章,幾個月前我已經開始撰寫代碼,所以如果我做錯了什么,我很抱歉..!我已經在網上瀏覽了幾天,但找不到答案(我的關鍵字可能選擇不當......)
為了提供一些背景關系,這是我從 csv 檔案中獲取我的 df 的方式:
#Library
import pandas as pd
import numpy as np
#Assisgn spreadsheets filenames and read files into a Dataframe
file_20 = '/Users/cortana/Desktop/Projet stage/DAT/dat_clean/donnees_assemblees_20.csv'
df_20_initial = pd.read_csv(file_20, sep=';', usecols=[0, 2, 3])
#Create dictionary with tables names as keys
tables_names_20 = pd.DataFrame.dropna(df_20_initial.iloc[:,[0]])
tables_names_20 = tables_names_20.set_index('20').T.to_dict()
#Slice the global dataframe and store the subsets into the dictionary as values
df_20_initial['separators'] = df_20_initial['time'].isna() #add a new column that check for missing values (separators)
print(df_20_initial)
這是我的 df 的樣子:
20 time velocity separators
0 P1S1 6.158655 0.136731 False
1 NaN 6.179028 0.244889 False
2 NaN 6.199253 0.386443 False
3 NaN 6.219323 0.571861 False
4 NaN 6.239505 0.777680 False
.. ... ... ... ...
520 NaN 7.008377 1.423408 False
521 NaN 7.028759 1.180113 False
522 NaN 7.048932 0.929300 False
523 NaN 7.068993 0.673909 False
524 NaN 7.089557 0.413527 False
[525 rows x 4 columns]
基于“分隔符”列中存在的布林值,我想創建一個包含“時間”和“速度”列的值的新資料框,當“分隔符”值為真時切片。
為此,我嘗試撰寫以下回圈未成功:
for lab, row in df_20_initial.iterrows() :
if df_20_initial.iloc[:,3] == False :
P1S1 = df_20_intermediate[['time', 'velocity']]
else :
break
...并從 Python 收到此錯誤訊息:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
歡迎任何建議,并提前感謝大家的時間!
uj5u.com熱心網友回復:
在我的實驗中,我使用了您的 DataFrame, 其中某些行中的分隔符設定為True :
20 time velocity separators
0 P1S1 6.158655 0.136731 False
1 NaN 6.179028 0.244889 False
2 NaN 6.199253 0.386443 False
3 NaN 6.219323 0.571861 True
4 NaN 6.239505 0.777680 False
5 NaN 7.008377 1.423408 False
6 NaN 7.028759 1.180113 False
7 NaN 7.048932 0.929300 True
8 NaN 7.068993 0.673909 False
9 NaN 7.089557 0.413527 False
我假設分隔符列是布爾型別。
要生成塊串列,您可以使用例如以下串列推導:
dfList = [ chunk[['time', 'velocity']] for _, chunk in
df_20_initial.groupby(df_20_initial.separators.cumsum()) ]
現在,當您例如列印dfList[1]時,您將獲得:
time velocity
3 6.219323 0.571861
4 6.239505 0.777680
5 7.008377 1.423408
6 7.028759 1.180113
但是,如果要洗掉分隔符行,請運行:
dfList2 = [ chunk[~chunk.separators][['time', 'velocity']] for _, chunk in
df_20_initial.groupby(df_20_initial.separators.cumsum()) ]
(從每個塊中只留下帶有分隔符 == False的行)。
uj5u.com熱心網友回復:
Pandas 非常擅長布爾切片。如果我正確理解您的問題,我認為您所需要的只是:
new_df = df_20_initial[df_20_initial['separators']]
如果要從輸出中洗掉“分隔符”列,只需選擇其余列,如下所示:
new_df = df_20_initial[df_20_initial['separators']][['time', 'velocity']]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/439920.html
