Home > Software engineering >  Is there any reason why this results in NaN instead of the str generated?
Is there any reason why this results in NaN instead of the str generated?

Time:10-23

Why does this result in NaN instead of a string?

df['rnd'] = df.apply(lambda x: str(random.randint(0,9999)).zfill(4))

rnd
---
NaN
NaN
NaN
NaN
NaN
df.dtypes
Rnd                 object

CodePudding user response:

If you just want a new random column (as zero-padded strings), you can vectorize it with numpy's randint (which accepts a size) and str.zfill, e.g.:

df = pd.DataFrame(np.random.random((4, 3)))

df['rnd'] = np.random.randint(0, 999, size=len(df))
df['rnd'] = df['rnd'].astype(str).str.zfill(4)

Output:

          0         1         2   rnd
0  0.696305  0.624101  0.235630  0056
1  0.437783  0.558600  0.451735  0913
2  0.061021  0.633813  0.008970  0509
3  0.944699  0.713951  0.478524  0088

CodePudding user response:

u need applymap not apply

df['rnd'] = df.applymap(lambda x: str(random.randint(0,9999)).zfill(4))

and this is the result

0    0179
1    4545
2    8510
3    3316
Name: rnd, dtype: object

if you want to use apply method then u need t specify the column to act on :

df["rnd"] = df.rnd.apply(lambda x: str(random.randint(0,9999)).zfill(4))

CodePudding user response:

It needed an axis.

df['rnd'] = df.apply(lambda x: str(random.randint(0,9999)).zfill(4), axis=1)
  • Related