first_card = '6212250200006032450' print(first_card) level_cards = pd.DataFrame({'卡级':[],'账号':[]}) print(level_cards) for first_cards in df.iloc[:,2]: if first_cards == first_card: level_cards['账号'] = first_cards
时间: 2024-03-18 20:39:46 浏览: 26
在这段代码中,`level_cards` 是一个空的 Pandas DataFrame,它包含两列,分别为 `'卡级'` 和 `'账号'`。在 `for` 循环中,我们对 `df` 的第三列进行迭代,如果其中的元素等于 `first_card`,则将 `first_cards` 赋值给 `level_cards` 的 `'账号'` 列。
然而,这段代码存在一个问题,即 `level_cards` 的 `'账号'` 列每次循环都会被赋值为当前迭代的 `first_cards`,而不是添加一个新的元素。因此,如果 `df` 中有多个与 `first_card` 相等的元素,最终 `level_cards` 的 `'账号'` 列将只包含最后一个相等的元素。
如果你想将所有相等的元素都添加到 `level_cards` 中,可以使用以下代码:
```
import pandas as pd
first_card = '6212250200006032450'
print(first_card)
level_cards = pd.DataFrame({'卡级':[],'账号':[]})
print(level_cards)
for index, row in df.iterrows():
if row[2] == first_card:
level_cards = level_cards.append({'卡级': row[1], '账号': row[2]}, ignore_index=True)
print(level_cards)
```
在这段代码中,我们使用了 Pandas 的 `iterrows()` 方法来迭代 `df` 的每一行。如果某一行的第三列等于 `first_card`,则将该行的第一列和第二列添加到 `level_cards` 中的新行中,并使用 `ignore_index=True` 参数来自动为新行分配一个新的索引。最终,`level_cards` 将包含所有与 `first_card` 相等的元素。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)