python-当切片有一行结果时返回pandas.DataFrame

前端之家收集整理的这篇文章主要介绍了python-当切片有一行结果时返回pandas.DataFrame 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

考虑以下:

  1. >>> import numpy as np
  2. >>> import pandas as pd
  3. >>> df = pd.DataFrame(np.random.randn(5,2),index=[100,101,102,103])
  4. >>> idx = set(df.index)
  5. >>> for id_ in idx:
  6. ... slice = df.loc[id_]
  7. ... # stuff with slice
  8. >>>

我需要在for循环中对slice进行处理,但是该操作是基于slice为DataFrame的.如果有多个匹配记录,则slice是一个DataFrame,否则为Series.我知道pandas.Series具有Seri​​es.to_frame方法,但pandas.DataFrame没有(所以我不能只调用df.loc [id _].to_frame()).

测试并将片段强制转换为DataFrame的最佳方法是什么?

(真的和测试isinstance(df.loc [id_],pd.Series)一样简单吗?)

最佳答案
您可以按索引(级别= 0)按groupby对象循环:

  1. for i,df1 in df.groupby(level=0):
  2. print (df1)
  3. 0 1
  4. 100 -0.812375 -0.450793
  5. 0 1
  6. 101 1.070801 0.217421
  7. 101 -1.175859 -0.926117
  8. 0 1
  9. 102 -0.993948 0.586806
  10. 0 1
  11. 103 1.063813 0.237741

您的解决方案应通过选择double []作为返回DataFrame来更改:

  1. idx = set(df.index)
  2. for id_ in idx:
  3. df1 = df.loc[[id_]]
  4. print (df1)
  5. 0 1
  6. 100 -0.775057 -0.979104
  7. 0 1
  8. 101 -1.549363 -1.206828
  9. 101 0.445008 -0.173086
  10. 0 1
  11. 102 1.488947 -0.79252
  12. 0 1
  13. 103 1.838997 -0.439362

猜你在找的Python相关文章