![](/img/trans.png)
[英]Create a new column in Pandas Dataframe based on the 'NaN' values in other columns
[英]Pandas create new column with values from other columns, selected based on column value
我有一個 dataframe 看起來有點像這個例子。 由於某些原因,原始數據具有復制的價值。
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 個節點,約 20,000 個值)。
我覺得必須有一種更快的方法,也許是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']])
使用DataFrame.lookup
然后DataFrame.assign
:
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
編輯:如果缺少某些值,您可以通過numpy.setdiff1d
為具有默認值的字典提取此值,例如np.nan
並在lookup
之前添加到 DataFrame :
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
定義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
並使用DataFrame.melt
解決方案:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.