简体   繁体   English

For 循环未写入 DataFrame (Python)

[英]For Loop not writing into DataFrame (Python)

I am trying to analyze some NBA data.我正在尝试分析一些 NBA 数据。 I have a CSV file with data and a field called "team" that has the team names and the place they finished in concatenated together in the same field.我有一个 CSV 文件,其中包含数据和一个名为“团队”的字段,其中包含团队名称和他们在同一字段中完成的位置。 I tried to write a for loop (below) to look at the final character and if it is a digit.我尝试编写一个 for 循环(如下)来查看最后一个字符以及它是否是一个数字。 For example, the Boston Celtics that finished in 2nd place would show up as "Boston Celtics2".例如,获得第二名的波士顿凯尔特人队将显示为“波士顿凯尔特人队2”。 Another example would be "New York Knicks11".另一个例子是“纽约尼克斯队11”。

for x in nba['team']:
        while x[-1].isdigit():
            print(x)
            x = x[:len(x)-1]
            print(x)

I included the print statements to make sure that it is slicing the data properly (which it is).我包含了打印语句以确保它正确地对数据进行切片(确实如此)。 But it is not writing back into my dataframe.但它没有写回我的 dataframe。 Why isn't it storing this back into my dataframe?为什么不将它存储回我的 dataframe 中?

>>> nba
                  team
0      Boston Celtics2
1    New York Knicks11
2  Los Angeles Lakers7

Remove trailing digits by ''.用''删除尾随数字。

nba['team'] = nba['team'].str.replace('\d+$', '')
>>> nba
                 team
0      Boston Celtics
1     New York Knicks
2  Los Angeles Lakers

It is not overwriting your DataFrame because in your for loop x only stores a copy of the value in your nba DataFrame.它不会覆盖您的 DataFrame,因为在您的 for 循环中 x 仅将值的副本存储在您的 nba DataFrame 中。 To change the value in your DataFrame you could loop with an index and change nba at the specific index:要更改 DataFrame 中的值,您可以使用索引循环并在特定索引处更改 nba:

for i, row in nba.iterrows():
    x = row['team'];
    while x[-1].isdigit():
        print(x)
        x = x[:len(x)-1]
        print(x)
    nba.at[i, 'team'] = x

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

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