繁体   English   中英

有没有办法使用 pandas dataframe 列中的值对字符串执行切片?

[英]Is there a way to use values in a pandas dataframe column to perform a slice of on a string?

我想用从字符串中提取的切片填充一列。
IE

df['unique'slice']= filler_slice[0:df[some_value']]

我有一个 dataframe 列,其中包含长度为 20:300 个字符的字符串。 我想让所有这些字符串的长度相同(300 个字符)。 额外的字符将来自定义的字符串。 我一直在尝试使用以下设置 300char 列,但它不起作用。 我得到一个错误长度的值与“”索引的长度不匹配。

我的代码如下所示:

filler_string='IAMA300CHARFILLERSTRING'.
df['300_string']=df['smaller_string']+filler_string[0:300-df['smaller_string_len']]

以下代码段可用于实现所述目标。 只是模拟你的问题。 可以修改代码的某些部分以适合您的代码。 为max_len重复填充字符串,以处理所需长度与实际长度之间的差异大于填充字符串长度的情况(如果填充字符串为最大长度,则可以省略)。

temp = {'string' : ['text1', 'text10', 'text123']}
df = pd.DataFrame(temp)
max_len = 300
filler_string='IAMA300CHARFILLERSTRING'
filler_string = (filler_string * (max_len // len(filler_string) + 1))[:max_len]
df['string'] = df['string'].apply(lambda x: "{}{}".format(x, filler_string[0:max_len - len(x)]))

你试过熊猫pad吗?

df['smaller_string'].str.pad(width=300, side='right', fillchar=your_char)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM