簡體   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