如何在pandas数据透视表中创建一个只包含匹配的填充列值的列?

2024-06-16 08:25:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个pandas pivot表,它列出了行中的个人和列中的数据源。有成百上千的人在一行一行地往下走,成百上千的信息源沿着纵队穿过。在

      Desired_Value  Source_1  Source_2  Source_3 ... Source_50
person1     20          20         20                    20
person2      5           5                    5           5
person3   Review         3          4         4           4
...
person50     1           1                                1

我要做的是在上面创建所需的\u Value列。我想拉入一个值,只要它与所有值匹配(忽略空白字段)。如果值不匹配,我要显示Review。在

我使用这个pandas命令将我的df当前打印到excel(没有任何所需的“值”列):

^{pr2}$

如果这是一个愚蠢的问题,我很抱歉。在


Tags: 命令sourcepandasvaluereview数据源空白pivot
1条回答
网友
1楼 · 发布于 2024-06-16 08:25:29

这是一种方法:

df = df13.copy()
df = df.astype('Int64') # So NaN and Int values can coexist

# Create new column at the front of the data frame
df['Desired_Value'] = np.nan
cols = df.columns.tolist()
cols = cols[-1:] + cols[:-1]
df = df[cols]

# Loop over all rows and flag columns for review
for idx, row in df.iterrows():
    val = row.dropna().unique()
    if len(val) == 1:
        df.loc[idx, 'Desired_Value'] = val
    else:
        df.loc[idx, 'Desired_Value'] = 'Review'

print(df)
^{pr2}$

相关问题 更多 >