python - 如何将 pandas 中的特定列值转换为列表?

标签 python list pandas dataframe

在以下pandas Dataframe中:

alfa  alfa_id    beta    beta_id
ak   23          ji    24
bc   24          kl    25

我想将 alfa 和 beta 列转换为列表。

cols = [l for l in df.columns.values if not l.endswith('id')]
df = df[cols].applymap(lambda c:[list(c)])
# gives me

我现在得到的输出:

print(df)

alfa      beta    
[[a, k]]  [[j, i]] 

** 但是,预期输出是:**

alfa      alfa_id    beta       beta_id
[[a, k]]   23        [[j, i]]    24
  • alfa_id 和 beta_id 的列丢失了,但我希望将它们恢复为一行代码(尽可能简单)。
  • 我正在寻找一种能够保持低内存占用的方法。

附注:我本来可以这样做

df = df.applymap(lambda c:[list(c)] if type(c) is str else c)

但是,我不想要这个,因为还有一些其他列不应转换为列表。因此,我想专门制作需要转换为列表的 cols 值。

谢谢

最佳答案

设置

cols = ['alfa', 'beta']

新答案

df.assign(**df[cols].stack().apply(list).unstack().to_dict('list'))

     alfa  alfa_id    beta  beta_id
0  [a, k]       23  [j, i]       24
1  [b, c]       24  [k, l]       25

旧答案

选项 1

df[cols].applymap(list)

选项 2

df[cols].stack().apply(list).unstack()

产量

     alfa    beta
0  [a, k]  [j, i]
1  [b, c]  [k, l]

关于python - 如何将 pandas 中的特定列值转换为列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42866712/

相关文章:

python - Python-版本列表而不是不可变列表?

python - Pandas - 填充 NaN 的变体 - 什么是优雅和 pythonic 的方式来做到这一点?

python - 用 Pandas 填补累积总和的空白

python - 一些 Plotly 绘图未在 JupyterLab 中显示

python - 在 Python 中遍历列表列表中的列

python - VS 代码 : how to make a python snippet that after string or expression hitting tab will transform it

python - 如何加速非常慢的 Pandas 应用功能?

python - 我如何编写给定代码的列表理解?

python - 在 python 列表迭代期间临时创建的?

r - 有没有一种方法可以自动将彼此下方的数据框列附加到大型数据框列表中的一列中?