2 回答

TA貢獻1712條經(jīng)驗 獲得超3個贊
您需要為每個單元格調(diào)用一次 get_ids,而不是為每一列調(diào)用一次:
df = pd.DataFrame({
'LeaseID': [gen_ids(10) for _ in range(1000)],
'PropertyID': [gen_ids(10) for _ in range(1000)],
'xyz': np.random.choice(List1, 1000),
'abc': np.random.choice(List2, 1000),
})
輸出是:
LeaseID PropertyID xyz abc
0 NHQikWbUZI phwUIn9IgZ 8 19
1 f6aBvrSeWe zV0tmst212 9 15
2 hdTHtm7LvU lC6uQJeHRX 8 14
3 FnppdLbbcq na9dVUO3Ay 2 17
4 arXAq4EvzT 7dvKTclo6o 1 18
...

TA貢獻1155條經(jīng)驗 獲得超0個贊
替代代碼:
gen_ids修改了問題中的函數(shù)以返回 a Series。
# Import libraries
import random
import string
import pandas as pd
import numpy as np
# Generate alphanumeric lease id and property ids
def gen_ids(length, len_df):
s = []
for i in range(len_df):
ids = ''.join(random.choices(string.ascii_letters + string.digits, k=length))
s.append(ids)
return s
# Create DataFrame
List1 = ['a','b','c','D','e']
List2 = ['G','h','k','L','q']
df = pd.DataFrame({
'LeaseID': gen_ids(10, 1000),
'PropertyID': gen_ids(10, 1000),
'xyz': np.random.choice(List1, 1000),
'abc': np.random.choice(List2, 1000)
})
輸出
print(df)
LeaseID PropertyID xyz abc
0 gxpSTdLoPH rswWVZuBIW a q
1 OSdR5vOA0I gHKdcYKw5s e L
2 WAmNQ4ieRH ThC1Apk5YA e h
3 BYUTgbKcbl IKcdjvH9da c L
4 4CNFqbu7hO uJEWhlEufu a k
.. ... ... .. ..
添加回答
舉報