pandas的Pathlib功能。
pandas-path的Python项目详细描述
pandas_path
-pandas的路径样式访问
爱^{
这个包裹是给你的。只需一次导入就可以向任何pandas系列或索引添加一个.path
访问器,这样就可以在Path
对象上使用所有方法。在
<;small>;*如果没有,您应该。<;/small>
下面是一个例子:
frompathlibimportPathimportpandasaspd# This is the only line you need to register `.path` as an accessor# on any Series or Index in pandas.importpandas_path# we'll make an example series from the py files in this repo;# note that every element here is just a string--no need to make Path objects yourselffile_paths=pd.Series(str(s)forsinPath().glob('**/*.py'))# 0 setup.py# 1 pandas_path/accessor.py# 2 pandas_path/test.py# dtype: object
使用.path
访问器只获取文件名而不是完整路径:
使用.path
访问器仅获取每个文件的父文件夹:
file_paths.path.parent# 0 .# 1 pandas_path# 2 pandas_path# dtype: object
使用exists
等计算方法筛选文件系统上存在的内容:
file_paths.loc[3]='fake_file.txt'# 0 setup.py# 1 pandas_path/accessor.py# 2 pandas_path/test.py# 3 fake_file.txt# dtype: objectfile_paths.path.exists()# 0 True# 1 True# 2 True# 3 False# dtype: bool
使用with_suffix
等路径方法动态创建新文件名:
file_paths.path.with_suffix('.png')# 0 setup.png# 1 pandas_path/accessor.png# 2 pandas_path/test.png# 3 fake_file.png# dtype: object
使用/
运算符,就像在pathlib
中一样(操作符的两边都有.path
访问器)
"different_root_folder"/file_paths.path# 0 different_root_folder/setup.py# 1 different_root_folder/pandas_path/accessor.py# 2 different_root_folder/pandas_path/test.py# dtype: object
我们甚至可以对相同长度的列表/数组/序列执行元素级操作。在
file_paths.path.parent.path/["other_file1.txt","other_file2.txt","other_file3.txt"]# 0 other_file1.txt# 1 pandas_path/other_file2.txt# 2 pandas_path/other_file3.txt# dtype: object
限制
- 虽然大多数操作都是开箱即用的,但使用
/
进行的运算符链接将无法按预期工作,因为我们总是返回序列本身,而不是访问器。在
file_paths.path.parent.path/"subfolder"/"other_file1.txt"# ----> 1 file_paths.path.parent.path / "subfolder" / "other_file1.txt"# ...# TypeError: unsupported operand type(s) for /: 'str' and 'str'
相反,请在结果上使用.path
访问器,或者在不链接的情况下重新写入:
(file_paths.path.parent.path/"subfolder").path/"other_file1.txt"# 0 subfolder/other_file1.txt# 1 pandas_path/subfolder/other_file1.txt# 2 pandas_path/subfolder/other_file1.txt# dtype: objectfile_paths.path.parent.path/"subfolder/other_file1.txt"# 0 subfolder/other_file1.txt# 1 pandas_path/subfolder/other_file1.txt# 2 pandas_path/subfolder/other_file1.txt# dtype: object
- 位于
/
左侧的numpy数组或pandas系列将无法正常工作。在
pd.Series(['a','b','c'])/pd.Series(['1','2','3']).path## IMPROPERLY BROADCASTS :'(# 0 0 a/1# 1 a/2# 2 a/3# dtype: object# 1 0 b/1# 1 b/2# 2 b/3# dtype: object# 2 0 c/1# 1 c/2# 2 c/3# dtype: object# dtype: object
相反,也可以使用右侧的路径访问器。在
pd.Series(['a','b','c']).path/pd.Series(['1','2','3']).path# 0 a/1# 1 b/2# 2 c/3# dtype: object
所有的人,享受吧!在
由您在Drivenda的朋友开发和维护!ml competitions| ai consulting
- 项目
标签: