簡體   English   中英

根據長度從字符串中刪除最后一位

[英]Remove last digit from String depending on length

如果字符串超過5位,我嘗試刪除df [4]字符串中的最后一位數字。

我嘗試將.str [:-1]添加到df [4] = df [4] .astype(str),這會刪​​除數據幀中每個字符串的最后一位。

df[3]=df[3].astype(str)
df[4]=df[4].astype(str).str[:-1]
df[5]=df[5].astype(str)

我嘗試了if語句的幾種不同組合,但沒有奏效。 我是python和pandas的新手,所以我們對您的幫助表示贊賞

您可以先根據字符串長度進行過濾:

condition = df[4].astype(str).str.len() > 5
df.loc[condition, 4]=df.loc[condition, 4].astype(str).str[:-1]

例如:

>>> df
           4
0          1
1         11
2        111
3       1111
4      11111
5     111111
6    1111111
7   11111111
8  111111111
>>> condition = df[4].astype(str).str.len() > 5
>>> df.loc[condition, 4]=df.loc[condition, 4].astype(str).str[:-1]
>>> df
          4
0         1
1        11
2       111
3      1111
4     11111
5     11111
6    111111
7   1111111
8  11111111

如果這些是自然整數,則除以10會更有效:

condition = df[4].astype(str).str.len() > 5
df.loc[condition, 4]=df.loc[condition, 4] // 10

訪問集合的元素

>>> x = "123456"

# get element at index from start
>>> x[0]
'1'

# get element at index from end
>>> x[-1]
'6'

# get range of elements from n-index to m-index
>>> x[0:3]
'123'
>>> x[1:-2]
'234'
>>> x[-4:-2]
'34'

# get range from/to index with open end/start
>>> x[:-2]
'1234'
>>> x[4:]
'56'

列表理解語法

我還沒有看到真正涼爽易懂的python列表理解語法

# input data frame with variable string length 1 to n
df = [
    'a',
    'ab',
    'abc',
    'abcd',
    'abcdf',
    'abcdfg',
    'abcdfgh',
    'abcdfghi',
    'abcdfghij',
    'abcdfghijk',
    'abcdfghijkl',
    'abcdfghijklm'
]

# using list comprehension syntax: [element for element in collection]
df_new = [
    # short hand if syntax: value_a if True else value_b
    r if len(r) <= 5 else r[0:5] 
    for r in df 
]

現在df_new僅包含長度為5的字符串:

[
 'a',
 'ab',
 'abc',
 'abcd',
 'abcdf',
 'abcdf',
 'abcdf',
 'abcdf',
 'abcdf',
 'abcdf',
 'abcdf',
 'abcdf'
]

導致[-1]刪除最后一個數字或將數字更改為-1嘗試str df[4]=-1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM