[英]How to return unique pairs from a dataframe based on another column's values?
我有一个数据框,如下所示:
Date A B Number
2017-01-01 a b 0.9240
2017-01-01 b c 0.9101
2017-01-01 d e 0.8761
2017-01-01 c g 0.9762
2017-01-02 b c 0.5637
2017-01-02 c d 0.9643
我想每天在A和B中都有一个唯一值的数据框,具体取决于数字列中的数字。 我认为逻辑将按以下顺序进行:
例如,从上面的数据框中看,由于2017年1月1日A列和B列中有一个'b',因此我想比较0.9240和0.9101并返回0.9240的行,因为它高于0.9101。
最终产品应如下所示:
Date A B Number
2017-01-01 a b 0.9240
2017-01-01 d e 0.8761
2017-01-01 c g 0.9762
2017-01-02 c d 0.9643
这很复杂,但是绝对有可能做到。
首先让我们确保数据的格式正确:
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 6 entries, 0 to 5
Data columns (total 4 columns):
Date 6 non-null datetime64[ns]
A 6 non-null object
B 6 non-null object
Number 6 non-null float64
dtypes: datetime64[ns](1), float64(1), object(2)
memory usage: 272.0+ bytes
请注意,“ Date
列的类型为datetime64
。 这是必需的,因为将这些值用作时间戳允许使用熊猫resample
方法每天对数据进行分组。
重新采样数据后,可以应用自定义方法extract
。 此方法将一组作为数据帧并应用逻辑。 通过使用pivot_table
方法,可以更轻松地找到A列和B列之间的交点。我不确定这是否是最有效的方法,但是如果数据集不是太大,它应该足够快地工作。
完整的代码如下所示:
def extract(df):
dfs = []
pt = df.reset_index().pivot_table('Number', columns=['A', 'B'], index='Date')
# find any intersection of values between col A and B
intersection = set(pt.columns.levels[0].values)\
.intersection(set(pt.columns.levels[1].values))
# iterate over all intersections to compare their values
# and choose the largest one
for value in intersection:
mask = (df['A'] == value) | (df['B'] == value)
df_intersection = df[mask]\
.sort_values('Number', ascending=False)
dfs.append(df_intersection.ix[[0]])
# find all rows that do not contain any intersections
df_rest = df[(~df['A'].isin(list(intersection))) &\
(~df['B'].isin(list(intersection)))]
if (len(df_rest) > 0):
dfs.append(df_rest)
return pd.concat(dfs)
df.set_index('Date')\
.resample('d')\
.apply(extract)\
.reset_index(level=1, drop=True)
此代码导致:
A B Number
Date
2017-01-01 a b 0.9240
2017-01-01 c g 0.9762
2017-01-01 d e 0.8761
2017-01-02 c d 0.9643
上面的代码基于给定的数据集:
import pandas as pd
from io import StringIO
data = StringIO("""\
Date A B Number
2017-01-01 a b 0.9240
2017-01-01 b c 0.9101
2017-01-01 d e 0.8761
2017-01-01 c g 0.9762
2017-01-02 b c 0.5637
2017-01-02 c d 0.9643
""")
df = pd.read_csv(data, sep='\s+', parse_dates=[0])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.