簡體   English   中英

python 用數字轉換列格式

[英]python convert column format with numeric

我有一個 dataframe df

姓名
項目111
項目212
項目'09
項目ws22

試圖將“項目”后非數字的列替換為無,output 如下:

姓名
項目111
項目212
沒有任何
沒有任何
沒有任何

如果這些缺失值是空字符串???,Pandas 不能識別為 null。 要解決此問題,您可以使用 replace() 將空字符串(或空單元格中的任何內容)轉換為 np.nan 對象,然后在 DataFrame 上調用 dropna() 以刪除具有 null 租戶的行。

使用正則表達式解決。

import pandas as pd
import re

df=pd.DataFrame(['project1','project2','project.3','projectws22'])
df.columns =['project']
for i in range(df.shape[0]):
   value = df.iloc[i,0]
   if re.search('project\d+',value):
      df.iloc[i,0]=re.search('project\d+',value).group(0)
   else:
      df.iloc[i,0]='none'

輸入

df
Out[33]: 
       project
0     project1
1     project2
2    project.3
3  projectws22

output

df
Out[31]: 
    project
0  project1
1  project2
2      none
3      none

有幾種方法可以解決這個問題。 最直接的是使用正則表達式來匹配只包含數字的列。 然后反轉生成的 boolean 數組並覆蓋這些值:

df.loc[~df["name"].str.fullmatch(r"project\d+"), "name"] = "none"
print(df)
         name
0  project111
1  project212
2        none
3        none

逐步分解:

# within the name column, find values that start with "project" 
#  and continue to any number of digits all the way to the end of the string.
>>> matches = df["name"].str.match(r"project\d+") 

# matches is a boolean array, indicating whether or not our pattern matches
#  the value in each cell of the column.
#  since we want to replace the values that DONT match the pattern, we use
#  the tilde operator to invert the boolean array (swap True's and False's
>>> ~matches

# Finally we replace those values with "none" by selecting the rows from the "name"
#  column that do not match the aforementioned pattern. Overwrite those cells with "none"
>>> df.loc[~matches, "name"] = "none"

使用列表comprehension的方法

代碼:

df['name'] = [df['name'][i] if (len(x)>1 and x[1].isdigit()) else None for i, x in enumerate(df['name'].str.split('project').values)]

Output:

         name
0  project111
1  project212
2        None
3        None
4        None

解釋:

  1. df['name'].str.split('project').valuesstring project存在的列名中拆分每個值並返回一個list
  2. 枚舉每個list以獲取該行的行索引和split操作的結果
  3. 檢查split結果是否有多個元素,以避免出現空行
  4. 檢查項目后的string ,即拆分結果中的第二個元素是否為數字
  5. 如果是,則返回行中的原始值,否則返回None

暫無
暫無

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

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