Development Tip

Pandas를 사용하여 두 열 비교

yourdevel 2020. 11. 29. 12:22
반응형

Pandas를 사용하여 두 열 비교


이것을 시작점으로 사용 :

a = [['10', '1.2', '4.2'], ['15', '70', '0.03'], ['8', '5', '0']]
df = pd.DataFrame(a, columns=['one', 'two', 'three'])

Out[8]: 
  one  two three
0   10  1.2   4.2
1   15  70   0.03
2    8   5     0

if팬더 내 에서 진술 과 같은 것을 사용하고 싶습니다 .

if df['one'] >= df['two'] and df['one'] <= df['three']:
    df['que'] = df['one']

기본적으로 if문을 통해 각 행을 확인하고 새 열을 만듭니다.

문서는 사용하라고 말하지만 .all예가 없습니다 ...


np.where 사용할 수 있습니다 . 경우 cond부울 배열하고, A그리고 B다음, 배열 인

C = np.where(cond, A, B)

C가 A어디가 condTrue이고 B어디가 condFalse인지를 정의합니다.

import numpy as np
import pandas as pd

a = [['10', '1.2', '4.2'], ['15', '70', '0.03'], ['8', '5', '0']]
df = pd.DataFrame(a, columns=['one', 'two', 'three'])

df['que'] = np.where((df['one'] >= df['two']) & (df['one'] <= df['three'])
                     , df['one'], np.nan)

수확량

  one  two three  que
0  10  1.2   4.2   10
1  15   70  0.03  NaN
2   8    5     0  NaN

조건이 두 개 이상인 경우 대신 np.select사용할 수 있습니다 . 예를 들어 다음 df['que']과 같을 df['two']df['one'] < df['two']

conditions = [
    (df['one'] >= df['two']) & (df['one'] <= df['three']), 
    df['one'] < df['two']]

choices = [df['one'], df['two']]

df['que'] = np.select(conditions, choices, default=np.nan)

수확량

  one  two three  que
0  10  1.2   4.2   10
1  15   70  0.03   70
2   8    5     0  NaN

df['one'] >= df['two']언제 df['one'] < df['two']가 False 라고 가정 할 수 있다면 조건과 선택을 다음과 같이 단순화 할 수 있습니다.

conditions = [
    df['one'] < df['two'],
    df['one'] <= df['three']]

choices = [df['two'], df['one']]

(가정은 NaN을 포함 df['one']하거나 df['two']포함하는 경우 사실이 아닐 수 있습니다 .)


참고

a = [['10', '1.2', '4.2'], ['15', '70', '0.03'], ['8', '5', '0']]
df = pd.DataFrame(a, columns=['one', 'two', 'three'])

문자열 값으로 DataFrame을 정의합니다. 숫자처럼 보이기 때문에 해당 문자열을 부동 소수점으로 변환하는 것이 더 나을 수 있습니다.

df2 = df.astype(float)

그러나 문자열은 문자별로 비교하고 부동 소수점은 숫자로 비교되기 때문에 결과가 변경됩니다.

In [61]: '10' <= '4.2'
Out[61]: True

In [62]: 10 <= 4.2
Out[62]: False

.equals열 또는 전체 데이터 프레임에 사용할 수 있습니다 .

df['col1'].equals(df['col2'])

같으면 해당 문은 True, else 를 반환 합니다 False.


apply () 사용하고 다음과 같이 할 수 있습니다.

df['que'] = df.apply(lambda x : x['one'] if x['one'] >= x['two'] and x['one'] <= x['three'] else "", axis=1)

또는 람다를 사용하지 않으려면

def que(x):
    if x['one'] >= x['two'] and x['one'] <= x['three']:
        return x['one']
    else:
        ''
df['que'] = df.apply(que, axis=1)

One way is to use a Boolean series to index the column df['one']. This gives you a new column where the True entries have the same value as the same row as df['one'] and the False values are NaN.

The Boolean series is just given by your if statement (although it is necessary to use & instead of and):

>>> df['que'] = df['one'][(df['one'] >= df['two']) & (df['one'] <= df['three'])]
>>> df
    one two three   que
0   10  1.2 4.2      10
1   15  70  0.03    NaN
2   8   5   0       NaN

If you want the NaN values to be replaced by other values, you can use the fillna method on the new column que. I've used 0 instead of the empty string here:

>>> df['que'] = df['que'].fillna(0)
>>> df
    one two three   que
0   10  1.2   4.2    10
1   15   70  0.03     0
2    8    5     0     0

Wrap each individual condition in parentheses, and then use the & operator to combine the conditions:

df.loc[(df['one'] >= df['two']) & (df['one'] <= df['three']), 'que'] = df['one']

You can fill the non-matching rows by just using ~ (the "not" operator) to invert the match:

df.loc[~ ((df['one'] >= df['two']) & (df['one'] <= df['three'])), 'que'] = ''

You need to use & and ~ rather than and and not because the & and ~ operators work element-by-element.

The final result:

df
Out[8]: 
  one  two three que
0  10  1.2   4.2  10
1  15   70  0.03    
2   8    5     0  

I think the closest to the OP's intuition is an inline if statement:

df['que'] = (df['one'] if ((df['one'] >= df['two']) and (df['one'] <= df['three'])) 

Use np.select if you have multiple conditions to be checked from the dataframe and output a specific choice in a different column

conditions=[(condition1),(condition2)]
choices=["choice1","chocie2"]

df["new column"]=np.select=(condtion,choice,default=)

Note: No of conditions and no of choices should match, repeat text in choice if for two different conditions you have same choices

참고URL : https://stackoverflow.com/questions/27474921/compare-two-columns-using-pandas

반응형