python - 索引 pandas DataFrame 的数组列

标签 python pandas dataframe indexing

我有一个 pandas DataFrame,其中包含一些数组列。建议通过不同的位置索引对其中一些列进行索引的方法是什么?例如,从名为 l 的数组列中,我需要第二个元素,从名为 a 的数组列中,我需要第一个元素。结果应该是一个新的 DataFrame。数组列可以包含 Python 列表或 Numpy 数组,但这可能并不重要。

我有三个解决方案,但我并不喜欢其中任何一个。

df= pd.DataFrame({'l': [[1, 2, 4], [3, 2, 0, 10]], \
                  'a':[np.array(["foo", "bar", "baz"]), np.array(["qux", "quux"])], \
                  'dontcare': [10, 20]})
               l                a  dontcare
0      [1, 2, 4]  [foo, bar, baz]        10
1  [3, 2, 0, 10]      [qux, quux]        20

解决方案 1,使用 strjoin

df['l'].str[1].to_frame('l').join(df['a'].str[0])
   l    a
0  2  foo
1  2  qux

解决方案 2,使用函数 apply 并创建系列

df.apply(lambda row: pd.Series([row['l'][1], row['a'][0]], index=['l', 'a']), axis=1)

解决方案 3,使用 applybroadcast

df[['l', 'a']].apply(lambda row: [row['l'][1], row['a'][0]], axis=1, result_type='broadcast')

我们可以假设输出列名称与输入列名称匹配,并且我们不需要任何数组列的多个元素。

最佳答案

我认为这取决于。

第一个解决方案是最通用的,如果索引不存在,则始终有效 - 然后返回 NaN。但这也是大型 DataFrame 解决方案最慢的原因。

print (df['l'].str[3].to_frame('l').join(df['a'].str[2]))
      l    a
0   NaN  baz
1  10.0  NaN

使用 apply 的另一个解决方案应该更快,但如果值不存在,则会失败。

print (df.apply(lambda row: pd.Series([row['l'][3], row['a'][2]], index=['l', 'a']), axis=1))

IndexError: ('list index out of range', 'occurred at index 0')

<小时/>

如果列表中始终存在值,另一个想法是使用列表理解(但与应用类似,如果不存在则失败)与 *c for tail :

df= pd.DataFrame({'l': [[1, 2, 4], [3, 2, 0, 10]], \
                  'a':[np.array(["foo", "bar", "baz"]), np.array(["qux", "quux"])], \
                  'dontcare': [10, 20],
                   's': [10, 20], 
                   'b': [10, 20]})
print (df)
               l                a  dontcare   s   b
0      [1, 2, 4]  [foo, bar, baz]        10  10  10
1  [3, 2, 0, 10]      [qux, quux]        20  20  20

df = pd.DataFrame([(a[1], b[0]) for a,b, *c in df.values], columns=['l', 'a'])
print (df)
   l    a
0  2  foo
1  2  qux

或者按列表选择列进行处理:

df = pd.DataFrame([(a[1], b[0]) for a,b in df[['l','a']].values], columns=['l', 'a'])

关于python - 索引 pandas DataFrame 的数组列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58851553/

相关文章:

python - Pandas 将每个数据集行乘以多个向量

python - 如何从值列表中将新列附加到 pandas groupby 对象

python - Django 模板过滤器查询集

python - 多对多的数据结构

python - 对大量文件进行近乎重复检查的最佳方法或算法?

python - Pandas groupby : can I select an agg function by one level of a column MultiIndex?

python - 使用 MultiIndex 在数据框中插入新列值?

python : nested json to dataframe

python - 根据原始数据框列数创建多个数据框

python - 如何让游戏角色(用户) Action 流畅?