# pandas中列不存在或列为NaN时根据行数据创建列

[英]Create column based on row data when column doesn't exist or column is NaN in pandas

TLDR：如果需要，我如何创建一个列，否则如何创建 map NaN？

``````import random
def setColor(_):
r = lambda: random.randint(0,255)
return '#%02X%02X%02X' % (r(),r(),r())

lines.loc[lines['colour'].isnull(),'colour'] = lines["colour"].map(setColor)
``````

``````import pandas as pd
import numpy as np
import random

df1 = pd.DataFrame({'Col_01': ['x', 'y', 'z']})
df2 = pd.DataFrame({'Col_01': ['x', 'y', 'z'], 'colour': ['#D30000', '#C21807', '']})

print("df1:\n", df1)
print("df2:\n", df2)
``````

``````df1:
Col_01
0      x
1      y
2      z
df2:
Col_01   colour
0      x  #D30000
1      y  #C21807
2      z
``````

``````def setColor(): # change: remove the "_" here
r = lambda: random.randint(0, 255)
return '#%02X%02X%02X' % (r(),r(),r())

for df in [df1, df2]:
if "colour" not in df:
df["colour"] = df.apply(lambda x: setColor(), axis=1)
else:
df["colour"] = np.where(df["colour"] == '', setColor(), df["colour"])

print("df1:\n", df1)
print("df2:\n", df2)
``````

``````df1:
Col_01   colour
0      x  #C0ACB3
1      y  #1FA09E
2      z  #4A35FF
df2:
Col_01   colour
0      x  #D30000
1      y  #C21807
2      z  #D97652
``````