簡體   English   中英

如何在不重復每一行的情況下訪問pandas數據框中的值

[英]how to access values in a pandas dataframe without iterating over each row

假設我有一個具有1000行和10列的Pandas Dataframe。

有5個標記為i1至i5的整數列和5個字符串列。

如何創建一個名為DIFF的新列,定義為

MAX(i1,i2,i3,i4,i5) - MIN(i1,i2,i3,i4,i5)

我在使用Max和Min運算符時遇到了麻煩,因為我沒有干凈地訪問值-被Series搞砸了。 在網上看到的其他例子中,人們在做

mydf.iloc[x]['SOME_COL'] 

要獲取單元格的值,但在此示例中,我不想遍歷行,我只想一次為每一行計算新列。

假設數字列是前5個,則可以使用以下方法獲得所需的列:

df.ix[:, 0:5].max(axis=1) - df.ix[:, 0:5].min(axis=1)

如果您真正感興趣的是采用數值列的最大值-最小值,則只需找出哪些列是數值列 ,然后對它們進行最大值-最小值即可。 像這樣:

>> df
   i1  i2  i3  i4  i5 str_col_1 str_col_2
0   1   2   3   4   5         a         b
1   1   2   3   4   5         a         b
2   1   2   3   4   5         a         b
3   1   2   3   4   5         a         b
4   1   2   3   4   5         a         b

>> numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
>> numeric_cols = df.select_dtypes(include=numerics)
>> numeric_cols.max(axis=1) - numeric_cols.min(axis=1)

0    4
1    4
2    4
3    4
4    4
dtype: int64

暫無
暫無

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

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