python - 使用基于列表名称的逻辑将列表转换为 DataFrame

标签 python pandas dataframe list-comprehension

我正在尝试从以下列表构建数据框:

A = ['item 1', 'item 2', 'item 3', 'item 4', 'item 5']

B = ['item 2','item 4']

C = ['item 1', 'item 5']

我希望列表名称(或该名称的某种表示)是相应的值,例如:

dA = [{'item':x, 'A':True} for x in A]
dB = [{'item':x, 'B':True} for x in B]
dC = [{'item':x, 'C':True} for x in C]

目前,我正在使用一些丑陋的方法构建我的数据框。我喜欢这里的最佳实践解决方案:

dfA = pd.DataFrame.from_records(dA)
dfB = pd.DataFrame.from_records(dB)
dfC = pd.DataFrame.from_records(dC)

df = pd.merge(dfA,dfB, 'outer').merge(dfC,'outer').fillna(False)

# Result:
    item    A   B   C
0   item 1  True    False   True
1   item 2  True    True    False
2   item 3  True    False   False
3   item 4  True    True    False
4   item 5  True    False   True

最佳答案

另一种不合并的方法

import pandas as pd

# list all unique items (in case there are not all present in A)
all_items = list(set(A+ B+C))
# create a dataframe with only item column
df = pd.DataFrame({'item':all_items})
# add boolean columns
df['A'] = df['item'].isin(A)
df['B'] = df['item'].isin(B)
df['C'] = df['item'].isin(C)

#   item    A   B   C
#0  item 4  True    True    False
#1  item 3  True    False   False
#2  item 2  True    True    False
#3  item 1  True    False   True
#4  item 5  True    False   True

如果你想要更漂亮的东西或者你有更多的列要创建,你也可以使用字典

dict_list = {'A': A, 'B': B, 'C':C}
for col in dict_list.keys():
  df[col] = df['item'].isin(dict_list[col])

关于python - 使用基于列表名称的逻辑将列表转换为 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58600154/

相关文章:

python - 在 Pandas Dataframe 中调用并分配特定变量

python - 如何选择 Pandas 数据框中的第一行?

python - 从另一个数据框中的列值替换 Pandas 数据框中列中的值

Python Pandas key 错误 : 'the label is not in the [index]'

python - 获取行 b_1 减去行 b_2 的差值最小的行 a

python - Python API 中的短语 "registering a callback"是什么意思?

python - 循环修改 OpenGL 小部件的按键输入

python - 在 Python 中对列表列表进行排序

python - pandas如何计算sem()?

python - 映射字典值,而不是字典键