在 pandas 中设置最大字符串长度 [英] Set max string length in pandas
本文介绍了在 pandas 中设置最大字符串长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望我的数据框自动截断长度超过特定长度的字符串.
I want my dataframe to auto-truncate strings which are longer than a certain length.
基本上:
pd.set_option('auto_truncate_string_exceeding_this_length', 255)
有什么想法吗?我有数百列,并且不想遍历每个数据点.如果可以在导入过程中做到这一点,也可以(例如pd.read_csv())
Any ideas? I have hundreds of columns and don't want to iterate over every data point. If this can be achieved during import that would also be fine (e.g. pd.read_csv())
谢谢.
推荐答案
您可以使用 read_csv转换器.假设您要截断列名abc
,则可以传递具有类似功能的字典
You can use read_csv converters. Lets say you want to truncate column name abc
, you can pass a dictionary with function like
def auto_truncate(val):
return val[:255]
df = pd.read_csv('file.csv', converters={'abc': auto_truncate}
如果您有不同长度的列
df = pd.read_csv('file.csv', converters={'abc': lambda: x: x[:255], 'xyz': lambda: x: x[:512]}
确保列类型为字符串.在转换器字典中,也可以使用列索引代替名称.
Make sure column type is string. Column index can also be used instead of name in converters dict.
这篇关于在 pandas 中设置最大字符串长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文