根据可变长度在 Pandas 数据框列中索引列表
Indexing lists in a Pandas dataframe column based on variable length
我在 Pandas 数据框中有一列由可变长度列表组成,我正在尝试找到一种根据列表长度提取元素的有效方法。考虑这个最小的可重现示例:
t = pd.DataFrame({'a':[['1234','abc','444'],
['5678'],
['2468','def']]})
假设我想将第二个元素(如果相关)提取到一个新列中,否则使用 NaN。我能够以非常低效的方式获得它:
_ = []
for index,row in t.iterrows():
if (len(row['a']) > 1):
_.append(row['a'][1])
else:
_.append(np.nan)
t['element_two'] = _
我尝试使用 np.where()
,但我没有正确指定 'if' 参数:
np.where(t['a'].str.len() > 1, lambda x: x['a'][1], np.nan)
对其他解决方案的更正和提示将不胜感激!我来自 R,在那里我认为矢量化是理所当然的。
我在 pandas 0.25.3 和 numpy 1.18.1。
虽然效率不高,但 apply
至少是干净的:
t['a'].apply(lambda _: np.nan if len(_)<2 else _[1])
使用 str
访问器:
n = 2
t['second'] = t['a'].str[n-1]
print(t)
a second
0 [1234, abc, 444] abc
1 [5678] NaN
2 [2468, def] def
我在 Pandas 数据框中有一列由可变长度列表组成,我正在尝试找到一种根据列表长度提取元素的有效方法。考虑这个最小的可重现示例:
t = pd.DataFrame({'a':[['1234','abc','444'],
['5678'],
['2468','def']]})
假设我想将第二个元素(如果相关)提取到一个新列中,否则使用 NaN。我能够以非常低效的方式获得它:
_ = []
for index,row in t.iterrows():
if (len(row['a']) > 1):
_.append(row['a'][1])
else:
_.append(np.nan)
t['element_two'] = _
我尝试使用 np.where()
,但我没有正确指定 'if' 参数:
np.where(t['a'].str.len() > 1, lambda x: x['a'][1], np.nan)
对其他解决方案的更正和提示将不胜感激!我来自 R,在那里我认为矢量化是理所当然的。
我在 pandas 0.25.3 和 numpy 1.18.1。
虽然效率不高,但 apply
至少是干净的:
t['a'].apply(lambda _: np.nan if len(_)<2 else _[1])
使用 str
访问器:
n = 2
t['second'] = t['a'].str[n-1]
print(t)
a second
0 [1234, abc, 444] abc
1 [5678] NaN
2 [2468, def] def