使用其他列中的值创建新列,这些值是根据列值选择的

2024-04-27 03:47:08 发布

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

我有一个数据帧,看起来有点像这个例子。由于某些原因,原始数据具有跨多个数据库复制的值

  Node Node 1 Value Node 2 Value Node 3 Value
0    1            A            B            C
1    2            A            B            C
2    3            A            B            C

我想将其转换为如下所示:

  Node Value
0    1     A
1    2     B
2    3     C

此iterrows代码按预期工作,但对于我的数据(48个节点,约20000个值)来说速度非常慢

我觉得必须有一个更快的方法,也许有apply,但我想不出来

import pandas as pd

df = pd.DataFrame({"Node": ["1", "2", "3"],
                   "Node 1 Value": ["A","A","A"],
                   "Node 2 Value": ["B","B","B"],
                   "Node 3 Value": ["C","C","C"]})

print(df)

for index, row in df.iterrows():
    df.loc[index, 'Value'] = row["Node {} Value".format(row['Node'])]

print(df[['Node','Value']])

Tags: 数据代码数据库nodedf原始数据index节点
1条回答
网友
1楼 · 发布于 2024-04-27 03:47:08

使用^{}然后使用^{}

a = df.lookup(df.index, "Node " + df.Node.astype(str) + " Value")

df = df[['Node']].assign(Value = a)
print (df)
   Node Value
0     1     A
1     2     B
2     3     C

编辑:如果缺少某些值,您可以通过^{}为具有默认值的字典提取这些值,例如np.nan,并在lookup之前添加到数据帧:

print (df)
   Node Node 1 Value Node 2 Value Node 3 Value
0     1            A            B            C
1     2            A            B            C
3     5            A            B            C

s = "Node " + df.Node.astype(str) + " Value"
new = dict.fromkeys(np.setdiff1d(s, df.columns), np.nan)
print (new)
{'Node 5 Value': nan}

print (df.assign(**new))
   Node Node 1 Value Node 2 Value Node 3 Value  Node 5 Value
0     1            A            B            C           NaN
1     2            A            B            C           NaN
3     5            A            B            C           NaN

a = df.assign(**new).lookup(df.index, s)
print (a)
['A' 'B' nan]

df = df[['Node']].assign(Value = a)
print (df)
   Node Value
0     1     A
1     2     B
3     5   NaN

关于definition of lookup的另一个想法是:

def f(row, col):
    try:
        return df.at[row, col]
    except:
        return np.nan

s = "Node " + df.Node.astype(str) + " Value"
a = [f(row, col) for row, col in zip(df.index, s)]

df = df[['Node']].assign(Value = a)
print (df)
   Node Value
0     1     A
1     2     B
3     5   NaN

^{}的解决方案:

s = "Node " + df.Node.astype(str) + " Value"
b = (df.assign(Node = s)
        .reset_index()
        .melt(['index','Node'], value_name='Value')
        .query('Node == variable').set_index('index')['Value'])


df = df[['Node']].join(b)
print (df)
   Node Value
0     1     A
1     2     B
3     5   NaN

相关问题 更多 >