我想在这个dataframe中添加一个新列“最佳”,其中包含符合以下条件的列的名称:
。
输入:
A B C
0 1 2 3
1 3 2 1
2 5 2 4
3 -3 0 2
4 6 3 4期望的结果:
A B C BEST
0 1 2 3 []
1 3 2 1 []
2 5 2 4 ['A']
3 -3 0 2 ['C']
4 6 3 4 ['A', 'B']对新列“最佳”中每一行的结果的解释:
生成数据的代码:
import io, pandas as pd
df = io.StringIO("""
A|B|C
1|2|3
3|2|1
5|2|4
-3|0|2
6|3|4
""")
df = pd.read_csv(df, sep='|')发布于 2021-06-16 03:30:47
您可以使用shift()、apply()和np.where来做到这一点。试试这个:
df['Best'] = (df - df.shift(2)).iloc[2:].apply(lambda x: list(df.columns[np.where(x==max(x))]), axis=1)输出:
print(df)
A B C Best
0 1 2 3 NaN
1 3 2 1 NaN
2 5 2 4 [A]
3 -3 0 2 [C]
4 6 3 4 [A, B]发布于 2021-06-16 03:29:19
首先使用shift和subtract获得差异,然后用列名替换最大值,然后删除其他值。
df['BEST'] = (
df.subtract(df.shift(2))
.apply(lambda x: [df.columns[i] for i,e in enumerate(x) if e==max(x)], axis=1)
)
A B C BEST
0 1 2 3 []
1 3 2 1 []
2 5 2 4 [A]
3 -3 0 2 [C]
4 6 3 4 [A, B]发布于 2021-06-16 03:29:35
尝试:
maximum=df.sub(df.shift(2)).max(skipna=False,axis=1)
#finded the maximum value
df['Best']=(df.where(df.sub(df.shift(2)).isin(maximum))
.T
.apply(lambda x:x.dropna().index.tolist()))df输出
A B C Best
0 1 2 3 []
1 3 2 1 []
2 5 2 4 [A]
3 -3 0 2 [C]
4 6 3 4 [A, B]https://stackoverflow.com/questions/67995888
复制相似问题