pandas 简单的方法来找到3个最大的值为一个给定的列与相应的值在另一列在我自己的格式

hiz5n14c  于 2023-10-14  发布在  其他
关注(0)|答案(2)|浏览(151)

假设我有一个DataFrame...

  1. data = {'PVOL': [190, 105, 100, 150, 100, 170], 'STKS': [2000, 2500, 3000, 3500, 4000, 4500],
  2. 'CVOL': [64, 179, 98, 281, 86, 90]}
  3. df = pd.DataFrame(data)

现在我想找到所有其他列的3个最大值(PVOL,CVOL...等,因为我的df也可能有多个其他列)和它们对应的列STKS的值,方式如下(作为字符串/打印):

  1. PVOL - 2000[190], 4500[170], 3500[150]
  2. CVOL - 3500[281], 2500[179], 3000[98]

我试着在DF格式中得到2个最大的值。

  1. columns_name = list(df.columns)
  2. columns_name.remove('STKS')
  3. data_dict = {}
  4. for col in columns_name:
  5. temp=[]
  6. data=df.sort_values(col, ascending=False)[:2][[col,'STKS']].values
  7. for row in data:
  8. temp.append(row[1])
  9. temp.append(row[0])
  10. data_dict[col]=temp
  11. new_df1=pd.DataFrame(data_dict,index="STK VOL STK VOL".split())
  12. new_df1.set_axis(["PVOL", "CVOL"], axis='columns', inplace=True)
  13. Vol_df = new_df1[["PVOL", "CVOL"]]
  14. print(Vol_df)

有没有简单的方法可以做到这一点???我也读到过...

  1. df.nlargest()

谢谢.

dz6r00yl

dz6r00yl1#

可以,你可以像这样使用nlargest方法:

  1. import pandas as pd
  2. data = {'PVOL': [190, 105, 100, 150, 100, 170],
  3. 'STKS': [2000, 2500, 3000, 3500, 4000, 4500],
  4. 'CVOL': [64, 179, 98, 281, 86, 90]}
  5. df = pd.DataFrame(data)
  6. result = {}
  7. for col in df.columns:
  8. if col != 'STKS':
  9. top_values = df.nlargest(3, col)
  10. result[col] = list(zip(top_values['STKS'], top_values[col]))
  11. result_df = pd.DataFrame(result)
  12. print(result_df)

输出:

  1. PVOL CVOL
  2. 0 (2000, 190) (3500, 281)
  3. 1 (4500, 170) (2500, 179)
  4. 2 (3500, 150) (3000, 98)

【编辑】:
以实现所需的特定输出格式

  1. import pandas as pd
  2. data = {'PVOL': [190, 105, 100, 150, 100, 170],
  3. 'STKS': [2000, 2500, 3000, 3500, 4000, 4500],
  4. 'CVOL': [64, 179, 98, 281, 86, 90]}
  5. df = pd.DataFrame(data)
  6. result = {}
  7. for col in df.columns:
  8. if col != 'STKS':
  9. top_values = df.nlargest(3, col)
  10. result[col] = ', '.join([f"{stk}[{val}]" for stk, val in zip(top_values['STKS'], top_values[col])])
  11. result_df = pd.Series(result)
  12. print(result_df)

输出:

  1. PVOL 2000[190], 4500[170], 3500[150]
  2. CVOL 3500[281], 2500[179], 3000[98]
展开查看全部
hmtdttj4

hmtdttj42#

nlargest中使用自定义函数:

  1. def f(s, n=3):
  2. x = s.nlargest(n)
  3. return ', '.join(f'{a}[{b}]' for a,b in zip(x.index, x))
  4. df.set_index('STKS').apply(f)

输出量:

  1. PVOL 2000[190], 4500[170], 3500[150]
  2. CVOL 3500[281], 2500[179], 3000[98]
  3. dtype: object

如果你想要字符串:

  1. for key, col in df.set_index('STKS').items():
  2. x = col.nlargest(3)
  3. s = ', '.join(f'{a}[{b}]' for a,b in zip(x.index, x))
  4. print(f'{key} - {s}')

输出量:

  1. PVOL - 2000[190], 4500[170], 3500[150]
  2. CVOL - 3500[281], 2500[179], 3000[98]

仅适用于列的子集:

  1. cols = ['CCHOI', 'PIV']
  2. for key, col in df.set_index('STKS')[cols].items():
  3. x = col.nlargest(3)
  4. s = ', '.join(f'{a}[{b}]' for a,b in zip(x.index, x))
  5. print(f'{key} - {s}')
展开查看全部

相关问题