python – Pandas列重新格式化

前端之家收集整理的这篇文章主要介绍了python – Pandas列重新格式化前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有快速实现以下输出方法

输入:

  1. Code Items
  2. 123 eq-hk
  3. 456 ca-eu; tp-lbe
  4. 789 ca-us
  5. 321 go-ch
  6. 654 ca-au; go-au
  7. 987 go-jp
  8. 147 co-ml; go-ml
  9. 258 ca-us
  10. 369 ca-us; ca-my
  11. 741 ca-us
  12. 852 ca-eu
  13. 963 ca-ml; co-ml; go-ml

输出

  1. Code eq ca go co tp
  2. 123 hk
  3. 456 eu lbe
  4. 789 us
  5. 321 ch
  6. 654 au au
  7. 987 jp
  8. 147 ml ml
  9. 258 us
  10. 369 us,my
  11. 741 us
  12. 852 eu
  13. 963 ml ml ml

我再次遇到循环和一个非常难看的代码,使其工作.如果有一种优雅的方式来实现这一点?

谢谢!

解决方法

  1. import pandas as pd
  2. df = pd.DataFrame([
  3. ('123','eq-hk'),('456','ca-eu; tp-lbe'),('789','ca-us'),('321','go-ch'),('654','ca-au; go-au'),('987','go-jp'),('147','co-ml; go-ml'),('258',('369','ca-us; ca-my'),('741',('852','ca-eu'),('963','ca-ml; co-ml; go-ml')],columns=['Code','Items'])
  4.  
  5.  
  6. # Get item type list from each row,sum (concatenate) the lists and convert
  7. # to a set to remove duplicates
  8. item_types = set(df['Items'].str.findall('(\w+)-').sum())
  9. print(item_types)
  10. # {'ca','co','eq','go','tp'}
  11.  
  12. # Generate a column for each item type
  13. df1 = pd.DataFrame(df['Code'])
  14. for t in item_types:
  15. df1[t] = df['Items'].str.findall('%s-(\w+)' % t).apply(lambda x: ''.join(x))
  16. print(df1)
  17.  
  18. # Code ca tp eq co go
  19. #0 123 hk
  20. #1 456 eu lbe
  21. #2 789 us
  22. #3 321 ch
  23. #4 654 au au
  24. #5 987 jp
  25. #6 147 ml ml
  26. #7 258 us
  27. #8 369 usmy
  28. #9 741 us
  29. #10 852 eu
  30. #11 963 ml ml ml

猜你在找的Python相关文章