2 回答

TA貢獻1868條經驗 獲得超4個贊
numpy是你的朋友。使用它并跳過 for 循環
# sample series
s = pd.Series([list('abcd'),
list('efgh'),
list('ijkl')])
# concat your series
l = np.concatenate(s)
array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'],
dtype='<U1')

TA貢獻2080條經驗 獲得超4個贊
它所做的只是展平列表列表,例如
nested_list = [[1, 2, 3],
[4],
[5, 6]]
flat_list = [item for inner_list in nested_list for item in inner_list]
# flat_list will be [1, 2, 3, 4, 5, 6]
要理解它,只需將其寫成嵌套的 for 循環即可:
result = []
for row in series:
for string in row:
result.append(string)
基本上它作為嵌套循環從左到右讀取,但內部代碼位于開頭。
您可以通過弄亂原始代碼中的間距來看到這一點:
result = [
string
for row in series # : <- pretend colons
for string in row # :
# result.append(string) <- this bit just goes to the start in list comprehension land
]
順便說一下,你顯然可以更快地使用itertools.chain(但我不確定這是否仍然適用于 a pd.Series):
import itertools
result = list(itertools.chain(*series.tolist()))
添加回答
舉報