繁体   English   中英

有没有更多的pythonic方式可以执行以下重复代码

[英]Is there any more pythonic way to do the following repetitive code

我有20列以上需要运行以下规则的列:

df['LAND1'] = df['LAND1'].str.replace('\W+', '')
df['LAND1'] = df['LAND1'].str.lower().astype(str)
df['SEA1'] = df['SEA1'].str.replace('\W+', '')
df['SEA1'] = df['SEA1'].str.lower().astype(str)
df['OCEAN1'] = df['OCEAN1'].str.replace('\W+', '')
df['OCEAN1'] = df['OCEAN1'].str.lower().astype(str)
df['CITY1'] = df['CITY1'].str.replace('\W+', '')
df['CITY1'] = df['CITY1'].str.lower().astype(str)

对于不同的列,使用更多相同类型的代码,如何最小化代码。 这样我可以写更少的代码。

您可以创建一个列名列表,然后遍历它们并对其应用逻辑。 范例-

columns = ['LAND1','SEA1','OCEAN1','CITY1',...]
for col in columns:
    df[col] = (df[col].str.replace('\W+', '')
                      .str.lower().astype(str))

演示-

In [17]: df
Out[17]:
         LAND1         SEA1
0  Blah!!!Bloh  Bleh@@@Blum
1  Blah!!!Bloh  Bleh@@@Blum
2  Blah!!!Bloh  Bleh@@@Blum
3  Blah!!!Bloh  Bleh@@@Blum
4  Blah!!!Bloh  Bleh@@@Blum
5  Blah!!!Bloh  Bleh@@@Blum
6  Blah!!!Bloh  Bleh@@@Blum
7  Blah!!!Bloh  Bleh@@@Blum
8  Blah!!!Bloh  Bleh@@@Blum
9  Blah!!!Bloh  Bleh@@@Blum

In [18]: columns = ['LAND1','SEA1']

In [20]: for col in columns:
   ....:     df[col] = (df[col].str.replace('\W+', '')
   ....:                       .str.lower().astype(str))
   ....:

In [21]: df
Out[21]:
      LAND1      SEA1
0  blahbloh  blehblum
1  blahbloh  blehblum
2  blahbloh  blehblum
3  blahbloh  blehblum
4  blahbloh  blehblum
5  blahbloh  blehblum
6  blahbloh  blehblum
7  blahbloh  blehblum
8  blahbloh  blehblum
9  blahbloh  blehblum

DataFrame.applyDataFrame.applymap也可以收缩您的代码:

df=pd.DataFrame({'A':['a','b','c'],'D':['d','e','f'],'G':['g','h','i']})
   A  D  G  
0  a  d  g
1  b  e  h
2  c  f  i

然后:

df.apply(pd.Series.replace,args=('d','ddd')).applymap(str.upper)

   A    D  G
0  A  DDD  G
1  B    E  H
2  C    F  I

您可以通过selection=['A','D']; df[selection]=df[selection].apply(....)来影响和限制某些列selection=['A','D']; df[selection]=df[selection].apply(....) selection=['A','D']; df[selection]=df[selection].apply(....)

我希望df是一dictionary

for i in df.keys():
    df[i]=df[i].str.replace('\W+', '')
    df[i]=df[i].str.lower().astype(str)

让我知道是否对您有帮助

融化数据框,然后将其应用于下层功能。 旋转数据框以返回

暂无
暂无

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

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