python - 使用 Numpy 迭代 DataFrame 行以创建新列

标签 python numpy for-loop

我正在尝试 reshape 数据框以使其成为更有用的图形结构,现在我一直在做的是使用 iterrows 或 itertuples reshape df,遵循 What is the most efficient way to loop through dataframes with pandas?

下面是一个过于简化的数据集,但真正的数据集会多出数万行。

group    subtopic    code
fruit    grapes      110A
fruit    apple       110B
meat     pork        220A
meat     chicken     220B
meat     duck        220C
vegetable lettuce    300A
vegetable tomato     310A
vegetable asparagus  320A

基本上,我想根据列(“code”)是否在列“group”中共享相同的值来创建一个新列(“code2”)。

我尝试运行以下代码:

df = pd.read_excel(file1, sheetname = 'Sheet3')

def reshape_iterrows(df):
    reshape = []

    for i, j, in df.iterrows():
        for _, k in df.iterrows():
            if (j['code'] == k['code']):
                pass
            elif j['group'] == 'nan':
                reshape.append({'code1':j['code'],
                       'code2': j['code'],
                       'group': 'None'})
            elif (j['group'] == k['group']):
                reshape.append({'code1': j['code'],
                       'code2': k['code'],
                       'group': j['group']})
            else:
                pass
        return reshape

reshape 迭代行(df)

或使用迭代元组:

def reshape_iterrows(df):
    reshape = []

    for row1 df.itertuples():
        for row2 in df.itertuples():
            if (row1[3] == row2[3]):
                pass
            elif row1[1] == 'nan':
                reshape.append({'code1':row1[3],
                       'code2': row1[3],
                       'group': 'None'})
            elif (row1[1] == row2[1]):
                reshape.append({'code1': row1[3],
                       'code2': row2[3],
                       'group': row1[1]})
            else:
                pass
        return reshape

我将 reshape 传递给 pd.DataFrame(),预期输出如下,然后我使用 code1 和 code2 列作为 nx.from_pandas_edgelist 中的源和目标参数来生成图形。

    code1   code2   group
0   110A    110B    fruit
1   110B    110A    fruit
2   220A    220B    meat
3   220A    220C    meat
4   220B    220A    meat
5   220B    220C    meat
6   220C    220A    meat
7   220C    220B    meat
8   300A    300B    vegetable
9   300A    300C    vegetable
10  300B    300A    vegetable
11  300B    300C    vegetable
12  300C    300A    vegetable
13  300C    300B    vegetable

和其他人一样,我有兴趣找到一种更有效的迭代方式,或许可以使用 Numpy 的 bool 运算?寻找有关如何使用向量化/数组操作获得相同结果的指导。

谢谢!

最佳答案

你可以试试:

from itertools import permutations
df.groupby('group')['code']\
  .apply(lambda x: pd.DataFrame(list(permutations(x.tolist(),2))))\
  .add_prefix('code').reset_index().drop('level_1',axis=1)

输出:

        group code0 code1
0       fruit  110A  110B
1       fruit  110B  110A
2        meat  220A  220B
3        meat  220A  220C
4        meat  220B  220A
5        meat  220B  220C
6        meat  220C  220A
7        meat  220C  220B
8   vegetable  300A  310A
9   vegetable  300A  320A
10  vegetable  310A  300A
11  vegetable  310A  320A
12  vegetable  320A  300A
13  vegetable  320A  310A

关于python - 使用 Numpy 迭代 DataFrame 行以创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54186988/

相关文章:

python - key 错误 : 'val_acc'

python - 在nestedExpr pyparsing中转义空格

java - 如何确保添加到数组的对象的 ID 不存在而不出现 nullpointerException?

EXCEL VBA - 遍历列中的单元格,如果不为空,则将单元格值打印到另一列

c - 我在 for 循环内使用 if -else 求和数组中的奇数时遇到问题

python - 在 `python` 上运行 R 代码,语法错误 : keyword can't be an expression error Message

python - 创建定义以替换 Python 句子中的单词

python - 优化嵌套循环操作

python - 为什么 Numpy 中的 0d 数组被视为标量?

python-2.7 - 对列表列表运行计算的最快方法