簡體   English   中英

如何從python中的數據幀中刪除特定的str?

[英]how to remove specific str from dataframe in python?

我正在處理每行包含“_”的數據框,例如:

    numbers
0   123
1   321_2
2   2222_2
3   41232_1
4   23123_5
5   45455
6   231231
7   3479_23_23
8   82837_212_fd

我的目的是刪除每行第一個“_”之后的所有字符串,例如:

    numbers
0   123
1   321
2   2222
3   41232
4   23123
5   45455
6   231231
7   3479
8   82837

然后我有了一個使用 'split' 函數的想法:

result = s.split("_")[0]

但是,它不能應用於數據幀,因為我收到了一個錯誤:AttributeError: 'DataFrame' object has no attribute 'split'

我的第一個問題是:如何在第一個“_”之后刪除 str?

此外,是否可以只刪除“_”但保留前導數字部分?

你可以做

df['numbers'] = df['numbers'].astype(str).str.split('_').str[0]
df
  numbers
0     123
1     321
2    2222
3   41232
4   23123
5   45455
6  231231
7    3479
8   82837

添加到BEN_YO的答案。

如果它是一個系列,您可以對其使用拆分功能。

lst = ['123','321_2','2222_2','41232_1','23123_5','45455','231231','3479_23_23','82837_212_fd']

s = pd.Series(lst)

s
0             123
1           321_2
2          2222_2
3         41232_1
4         23123_5
5           45455
6          231231
7      3479_23_23
8    82837_212_fd
dtype: object
s.str.split('_').str[0]
0       123
1       321
2      2222
3     41232
4     23123
5     45455
6    231231
7      3479
8     82837
dtype: object

但是,如果是數據框,則使用相同的方法替換值。

df['numbers'] # 返回一個系列,我們正在該系列上應用拆分函數。

df = pd.Series(lst).to_frame('numbers')
type(df['numbers'])
pandas.core.series.Series
df['numbers'] = df['numbers'].str.split('_').str[0]
print(df)
  numbers
0     123
1     321
2    2222
3   41232
4   23123
5   45455
6  231231
7    3479
8   82837

暫無
暫無

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

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