鱼C论坛

 找回密码
 立即注册
查看: 2989|回复: 17

[已解决]可以把series的值调换位置吗?

[复制链接]
发表于 2023-2-4 09:24:51 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
有一个series
<bound method Series.info of 2      2065
11      1120
12      1044
14       970
13       908
98      898
16       652
17       519
Name: 数量, dtype: int64>

可以把它的两个值调换过来吗?换成这样

<bound method Series.info of 2065    2
1120                11      
1044                12      
970                14      
908                13      
898                98      
652                16      
519                17      
Name: 数量, dtype: int64>

该怎么写代码,用什么函数来调换它们的位置。
最佳答案
2023-2-4 10:26:39
本帖最后由 isdkz 于 2023-2-4 10:42 编辑

import pandas as pd
s = pd.Series([2065, 1120, 1044, 970, 908, 898, 652, 519])
print("转换前:")
print(s.info)

print()
#  转换的代码,实现原理是修改 pandas 用于格式化输出的源码把 fmt_index[1:] 和 fmt_values 调换,执行后永久生效,你可以看代码的实现过程,后面可以自己改回来
import fileinput
for line in fileinput.input(pd.io.formats.format.__file__, backup='.bak', inplace=1):
    if line != '            result = self.adj.adjoin(3, *[fmt_index[1:], fmt_values])\n':
        print(line, end='')
    else:
        print('            result = self.adj.adjoin(3, *[fmt_values, fmt_index[1:]])')
pd.io.formats.format.__spec__.loader.load_module()
print("转换后:")
print(s.info)

效果:
转换前:
<bound method Series.info of 0    2065
1    1120
2    1044
3     970
4     908
5     898
6     652
7     519
dtype: int64>

转换后:
<bound method Series.info of  2065   0
1120   1
1044   2
  970   3
  908   4
  898   5
  652   6
  519   7
dtype: int64>
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2023-2-4 09:25:12 | 显示全部楼层
麻烦大家给个主意,谢谢
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-2-4 10:26:39 | 显示全部楼层    本楼为最佳答案   
本帖最后由 isdkz 于 2023-2-4 10:42 编辑

import pandas as pd
s = pd.Series([2065, 1120, 1044, 970, 908, 898, 652, 519])
print("转换前:")
print(s.info)

print()
#  转换的代码,实现原理是修改 pandas 用于格式化输出的源码把 fmt_index[1:] 和 fmt_values 调换,执行后永久生效,你可以看代码的实现过程,后面可以自己改回来
import fileinput
for line in fileinput.input(pd.io.formats.format.__file__, backup='.bak', inplace=1):
    if line != '            result = self.adj.adjoin(3, *[fmt_index[1:], fmt_values])\n':
        print(line, end='')
    else:
        print('            result = self.adj.adjoin(3, *[fmt_values, fmt_index[1:]])')
pd.io.formats.format.__spec__.loader.load_module()
print("转换后:")
print(s.info)

效果:
转换前:
<bound method Series.info of 0    2065
1    1120
2    1044
3     970
4     908
5     898
6     652
7     519
dtype: int64>

转换后:
<bound method Series.info of  2065   0
1120   1
1044   2
  970   3
  908   4
  898   5
  652   6
  519   7
dtype: int64>
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-2-4 10:28:41 | 显示全部楼层
应该在导入的时候就分清index和data
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-2-4 11:14:37 | 显示全部楼层

按您的代码,试运行下,运行后出现
转换前:
<bound method Series.info of 0    2065
1    1120
2    1044
3     970
4     908
5     898
6     652
7     519
dtype: int64>

Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\Scripts\转换位置.py", line 9, in <module>
    for line in fileinput.input(pd.io.formats.format.__file__, backup='.bak', inplace=1):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\fileinput.py", line 251, in __next__
    line = self._readline()
           ^^^^^^^^^^^^^^^^
UnicodeDecodeError: 'gbk' codec can't decode byte 0x9d in position 2907: illegal multibyte sequence

进程已结束,退出代码1

请问下,该如何解决?
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-2-4 11:18:24 | 显示全部楼层
本帖最后由 isdkz 于 2023-2-4 11:20 编辑
skyhouse 发表于 2023-2-4 11:14
按您的代码,试运行下,运行后出现
转换前:


编码问题:加个参数encoding指定编码

修改后的代码:
import pandas as pd
s = pd.Series([2065, 1120, 1044, 970, 908, 898, 652, 519])
print("转换前:")
print(s.info)

print()
#  转换的代码,实现原理是修改 pandas 用于格式化输出的源码把 fmt_index[1:] 和 fmt_values 调换,执行后永久生效,你可以看代码的实现过程,后面可以自己改回来
import fileinput
for line in fileinput.input(pd.io.formats.format.__file__, backup='.bak', inplace=1, encoding='utf-8'):
    if line != '            result = self.adj.adjoin(3, *[fmt_index[1:], fmt_values])\n':
        print(line, end='')
    else:
        print('            result = self.adj.adjoin(3, *[fmt_values, fmt_index[1:]])')
pd.io.formats.format.__spec__.loader.load_module()
print("转换后:")
print(s.info)
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-2-4 11:58:42 | 显示全部楼层
isdkz 发表于 2023-2-4 11:18
编码问题:加个参数encoding指定编码

修改后的代码:

请问怎么改回来格式化输出的源码,我执行其他py文件会报错。
刚刚重装了python跟pycharm,还是会报错。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-2-4 12:03:42 | 显示全部楼层
本帖最后由 isdkz 于 2023-2-4 12:04 编辑
skyhouse 发表于 2023-2-4 11:58
请问怎么改回来格式化输出的源码,我执行其他py文件会报错。
刚刚重装了python跟pycharm,还是会报错。


会报错可能是因为你的pandas跟我的pandas版本不一致,所以代码也有点不一样

C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\io\formats\format.py

你把这个文件第 409 行(包括第 409 行前后的)内容复制出来给我看看

或者把报错信息放上来
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-2-4 12:42:12 | 显示全部楼层
isdkz 发表于 2023-2-4 12:03
会报错可能是因为你的pandas跟我的pandas版本不一致,所以代码也有点不一样

C:%users\Administrator ...

format文件 399行开始
        if self.is_truncated_vertically:
            n_header_rows = 0
            row_num = self.tr_row_num
            row_num = cast(int, row_num)
            width = self.adj.len(fmt_values[row_num - 1])
            if width > 3:
                dot_str = "..."
            else:
                dot_str = ".."
            # Series uses mode=center because it has single value columns
            # DataFrame uses mode=left
            dot_str = self.adj.justify([dot_str], width, mode="center")[0]
            fmt_values.insert(row_num + n_header_rows, dot_str)
            fmt_index.insert(row_num + 1, "")

        if self.index:
            result = self.adj.adjoin(3, *[fmt_values, fmt_index[1:]])
        else:
            result = self.adj.adjoin(3, fmt_values)

        if self.header and have_header:
            result = fmt_index[0] + "\n" + result

        if footer:
            result += "\n" + footer

        return str("".join(result))


报错信息是:
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\__init__.py", line 48, in <module>
    from pandas.core.api import (
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\api.py", line 47, in <module>
    from pandas.core.groupby import (
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\groupby\__init__.py", line 1, in <module>
    from pandas.core.groupby.generic import (
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\groupby\generic.py", line 76, in <module>
    from pandas.core.frame import DataFrame
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\frame.py", line 171, in <module>
    from pandas.core.generic import NDFrame
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\generic.py", line 147, in <module>
    from pandas.core.describe import describe_ndframe
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\describe.py", line 45, in <module>
    from pandas.io.formats.format import format_percentiles
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\io\formats\format.py", line 991
   
    ^
IndentationError: expected an indented block after 'if' statement on line 990
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-2-4 12:49:23 | 显示全部楼层
isdkz 发表于 2023-2-4 12:03
会报错可能是因为你的pandas跟我的pandas版本不一致,所以代码也有点不一样

C:%users\Administrator ...

刚刚发现format文件有个备份,在你刚刚的程序中有备份bak,改下后缀能用。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-2-4 12:50:56 | 显示全部楼层
skyhouse 发表于 2023-2-4 12:42
format文件 399行开始
        if self.is_truncated_vertically:
            n_header_rows = 0


我之前的代码有做个备份的,你把
C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\io\formats\format.py 删掉
C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\io\formats\format.py.bak 这个文件的 .bak 去掉


然后你想把索引显示在右边的话就改下面标红的那一句,我就是把 fmt_values 和 fmt_index[1:] 的位置做了调换,你后面要改回来的话可以调换回来

format文件 399行开始
        if self.is_truncated_vertically:
            n_header_rows = 0
            row_num = self.tr_row_num
            row_num = cast(int, row_num)
            width = self.adj.len(fmt_values[row_num - 1])
            if width > 3:
                dot_str = "..."
            else:
                dot_str = ".."
            # Series uses mode=center because it has single value columns
            # DataFrame uses mode=left
            dot_str = self.adj.justify([dot_str], width, mode="center")[0]
            fmt_values.insert(row_num + n_header_rows, dot_str)
            fmt_index.insert(row_num + 1, "")

        if self.index:
            result = self.adj.adjoin(3, *[fmt_index[1:]], fmt_values)             # 这一句改成 result = self.adj.adjoin(3, *[fmt_values, fmt_index[1:]])   
        else:
            result = self.adj.adjoin(3, fmt_values)

        if self.header and have_header:
            result = fmt_index[0] + "\n" + result

        if footer:
            result += "\n" + footer

        return str("".join(result))
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-2-4 12:51:11 | 显示全部楼层
isdkz 发表于 2023-2-4 12:03
会报错可能是因为你的pandas跟我的pandas版本不一致,所以代码也有点不一样

C:%users\Administrator ...

这个方法比较伤筋动骨,有没其他方法?运行效率慢点也能接受。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-2-4 12:53:25 | 显示全部楼层
本帖最后由 isdkz 于 2023-2-4 15:34 编辑
skyhouse 发表于 2023-2-4 12:51
这个方法比较伤筋动骨,有没其他方法?运行效率慢点也能接受。


暂时没有发现其它方法,那个改源码也就改一个地方而已,我就是怕你不会改才写了个代码的,

没想到那个代码跟你的 pandas 不通用
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-2-4 15:14:30 | 显示全部楼层
isdkz 发表于 2023-2-4 12:53
暂时没有发现其它方法,那个改源码也就改一个地方而已,我就是怕你不会改才写了个代码的,

没想带那个 ...

谢谢你,我静等其他大神给解决方法
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-2-4 15:37:29 | 显示全部楼层
import pandas as pd

data = [11, 12, 13]
index = [100, 200, 300]
s = pd.Series(data, index=index)
print(s)

s2 = pd.Series(s.index, index=s.values)
print(s2)
这种数据和index应该是在导入时解决的问题,不应该交给pandas.
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-2-4 16:51:33 | 显示全部楼层
suchocolate 发表于 2023-2-4 15:37
这种数据和index应该是在导入时解决的问题,不应该交给pandas.


他的意思大概是想把索引显示在右边,而不是把索引和数据调换
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-2-4 21:42:35 | 显示全部楼层
isdkz 发表于 2023-2-4 16:51
他的意思大概是想把索引显示在右边,而不是把索引和数据调换

好吧
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-2-4 22:11:15 | 显示全部楼层
谢谢各位的回答,感谢。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-24 19:15

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表