簡體   English   中英

如何在 Pandas 中使用 if、elif 和 else 語句

[英]how to use if, elif and else statement in pandas

我有一個包含 6250 行和 275 列的數據集。

假設我有一列:

Time
0.0
0.0
0.0
18:56.5

使用df = pd.read_clipboard(sep=',')讀取數據

我在嘗試着:

  1. 傳遞一個條件,如果第 1 行為 0,則打印第 2 行
  2. 如果第 2 行也有 0,則打印第 3 行

我試了好幾次,都沒有結果。

我試過如下:

t = record['Time'].iloc[0]
t1 = record['Time'].iloc[1]
t2 = record['Time'].iloc[2]
t3 = record['Time'].iloc[3]

if t != 0:
    print ('Start_time: ', t)
elif t1 != 0: 
    print('Start_time: ', t1)
elif t2 != 0:
    print('Start_time: ', t2)
else: 
    print('Start_time: ',t3) 

它不顯示任何錯誤,結果只打印t's值。 它沒有通過條件。

我也試過:

if t <= 0:
    print ('Start_time: ', t)
elif t1 <= 0: 
    print('Start_time: ', t1)
elif t2 <= 0:
    print('Start_time: ', t2)
else: 
    print('Start_time: ',t3) 

它指出:

類型錯誤:“str”和“int”的實例之間不支持“<=”

循環 if 語句

如果“if, elif, else conditions”滿足任一條件,則不檢查剩余條件。 所以上面的代碼只顯示了 t 的值作為結果。 您必須檢查每個 if 語句的所有值。

for i in range(4):
    t = record['Time'].iloc[i]
    t = float(t) # t seems like "str" type, you mentioned type error.
    if t != 0:
        print("At t{}, start_time : {}".format(i, t))

熊貓情況

record[record['Time'] != 0]

它將顯示您想要的記錄。

看看這是否適合你。 這僅在時間格式有冒號而不是點時才有效。 我已將 18:56.5 更改為 18:56:5(56 之后的冒號而不是點)。

df['Time']= pd.to_datetime(df['Time'], format='%H:%M:%S',errors='coerce').fillna(0)
for index, row in df.iterrows():
    if row['Time']!= 0:
        print(row['Time'].strftime("%H:%M:%S"))
    else:
       pass
  1. 你的問題是,如何在pandas使用ifelifelse
    • 看起來你真正想做的是返回值!='0.0'
  2. 遍歷DataFrame是一個糟糕的主意,因為它效率不高。
  3. 顯示的數據格式不正確!
    • 0.013:15.3不是時間格式
    • 它都是objectstr類型,所以t1 <= 0將不起作用。
    • pd.to_datetime也不起作用。
df = pd.DataFrame({'Time': ['0.0', '0.0', '0.0', '18:56.5', '0.0', '0.0', '07:45.4'],
                   'Time2': ['0.0', '13:15.3', '0.0', '17:03.0', '0.0', '0.0', '07:45.4']})

在此處輸入圖片說明

創建一個DataFrames dict

  • 以下代碼查看每一列並將DataFrame添加到df_dict keys是來自dfcolumn名, values是一切!= '0.0'
df_dict = dict()

for x in df.columns:
    df_dict[x] = df[x][df[x] != '0.0']  # .reset_index(drop=True) can be added here

df_dict輸出:

df_dict['Time']
3    18:56.5
6    07:45.4
Name: Time, dtype: object


df_dict['Time2']
1    13:15.3
3    17:03.0
6    07:45.4
Name: Time2, dtype: object

將其全部合並為一個DataFrame

df_all = pd.concat([v for _, v in df_dict.items()], axis=1)

在此處輸入圖片說明

  1. .reset_index(drop=True)將解決索引號問題
  2. 每列中的值數量可能不同,因此列長度不會對齊。 如果索引被重置, df_all的末尾將有NaN值填充列的末尾。

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM