我試圖將包含特定日期時間值的所有行添加到一個串列中,然后列印該串列。我遍歷資料框架中的所有行,在某一列中尋找一個特定的值。如果該值出現,我想將該特定行添加到串列中。
代碼:
with open('Layer1.csv'/span>, newline = ') as csvfile2:
df = pd.read_csv('Layer1.csv')
AudioMothIDs = getID()
AudioMothIDs.remove('NA')
csv_reader = csv.reader(csvfile2)
for row in csv_reader:
orig_list = []
#迭代每個唯一的ID。
for x in AudioMothIDs:
ID_df = df[df['AudioMothID'] == x)
#Iterates through all rows in the ID dataframe
for index, rows in ID_df.iterrows() 。
#在StartDateTime列中搜索一個特定的DateTime。
if '16.06.2019 15:00' in ID_df.StartDateTime. values:
#Attempts to add rows with the specific DateTime to a list[/span].
current_list = [rows.AudioMothID,rows.StartDateTime] 。
orig_list.append(current_list)
print( orig_list)
Appending rows.AudioMothID和rows.StartDatetime將ID內的所有記錄追加到串列中,而不是只追加StartDateTime列中有'16.06.2019 15:00'的記錄。我也嘗試過使用 ID_df.iloc[index],它同樣會添加所有記錄,而不是只添加包含指定字串的記錄。
我怎樣才能只將包含 StartDateTime 列中的'16.06.2019 15:00'的行追加到串列中?
uj5u.com熱心網友回復:
你的代碼可以被濃縮,使之更符合pandas的習慣。也許像這樣:
# Load CSV into a pandas DataFrame, no need for csv.reader or with open()
df = pd.read_csv('Layer1.csv'/span>)
# 復制所有具有所需的StartDateTime的行作為一個新的DataFrame。
res = df[df['StartDateTime'] == '16.06.2019 15:00'].copy()
print(res)
uj5u.com熱心網友回復:
我認為你做了很多不必要的步驟,例如,讀取兩次csv檔案,迭代每一行,然后迭代每一個ID。
讓我們簡單地使用pandas來實作:
# read dataframe using pandas
df = pd.read_csv('Layer1.csv'/span>)
# 過濾日期,選擇特定列并轉換為串列。
df[df.StartDateTime == '16.06.2019 15:00'][[df.AudioMothID, df.StartDateTime]]. values.tolist()
[EDIT]針對你的評論進行補充:
# ensure date column is in the right format<
df['StartDateTime'] = pd.to_datetime(df['StartDateTime'] )
#按日期的小時數過濾。
df[df.StartDateTime.dt.hour ==15]
- 如何對每個小時和每個ID進行隨機抽樣 。
# ensure date column is in right format.
df['StartDateTime'] = pd.to_datetime(df['StartDateTime'] )
# 將日期列四舍五入到最近的小時。
df['StartDateTime_nearest_hour'] = df['StartDateTime'].dt.round('H')
# 按每天的每個小時和ID隨機抽取1個樣本。
df.groupby(['AudioMothID', 'StartDateTime_nearest_hour'].pleam(n=1)
# 如果你想對隨機一天中的一個小時進行采樣,而不是:
df['StartDateTime_hour'] = df['StartDateTime'].dt.hour
df.groupby(['AudioMothID', 'StartDateTime_hour'].pleam(n=1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/309985.html
標籤:
