簡體   English   中英

遍歷數據框

[英]Iterate through data frame

我的代碼拉出一個數據框對象,我想屏蔽該數據框。 如果值 <= 15,則將值更改為 1,否則將值更改為 0。

import pandas as pd
XTrain = pd.read_excel('C:\\blahblahblah.xlsx')

for each in XTrain:
  if each <= 15:
    each = 1
  else:
    each = 0

我來自 VBA 和 .NET,所以我知道它不是很 Pythonic,但對我來說似乎非常容易......代碼遇到錯誤,因為它遍歷 df 標頭。 所以我試圖檢查類型

for each in XTrain:
  if isinstance(each, str) is False:
    if each <= 15:
      each = 1
    else:
      each = 0

這次它到達了最后的標頭,但沒有進入數據幀。 這讓我覺得我沒有正確循環遍歷 thr 數據幀? 被難住了幾個小時,有人可以給我一點幫助嗎?

謝謝!

for each in XTrain總是通過列名的循環。 這就是 Pandas 的設計方式。

Pandas 允許直接與數字進行比較/算術運算。 所以你要:

 # le is less than or equal to
 XTrains.le(15).astype(int)

 # same as
 # (XTrain <= 15).astype(int)

如果您真的想迭代(不要),請記住數據幀是二維的。 所以像這樣:

for index, row in df.iterrows():
    for cell in row:
        if cell <= 15:
            # do something
            # cell = 1 might not modify the cell in original dataframe
            # this is a python thing and you will get used to it
        else:
            # do something else
        

設置

df = pd.DataFrame({'A' : range(0, 20, 2), 'B' : list(range(10, 19)) + ['a']})
print(df)

    A   B
0   0  10
1   2  11
2   4  12
3   6  13
4   8  14
5  10  15
6  12  16
7  14  17
8  16  18
9  18   a

解決方案pd.to_numeric避免 str 值和DataFrame.le出現問題

df.apply(lambda x: pd.to_numeric(x, errors='coerce')).le(15).astype(int)

輸出

   A  B
0  1  1
1  1  1
2  1  1
3  1  1
4  1  1
5  1  1
6  1  0
7  1  0
8  0  0
9  0  0

如果要保留字符串值:

df2 = df.apply(lambda x: pd.to_numeric(x, errors='coerce'))
new_df = df2.where(lambda x: x.isna(), df2.le(15).astype(int)).fillna(df)
print(new_df)


   A  B
0  1  1
1  1  1
2  1  1
3  1  1
4  1  1
5  1  1
6  1  0
7  1  0
8  0  0
9  0  a

使用applymap將函數應用於數據幀的每個元素,並使用lambda編寫函數。

df.applymap(lambda x: x if isinstance(each, str) else 1 if x <= 15 else 0)

暫無
暫無

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

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