python - Pandas,结合来自 2 个数据帧和一本字典的信息

标签 python pandas dictionary dataframe string-comparison

这有点难以解释......

假设您有 2 个 pandas 数据框和 1 个字典。

df1 = pd.DataFrame(np.random.randn(5, 3), columns=['b', 'c','d'])
df1['a'] = pd.Series(['1 A1-1','3 A1-1','8 A1-2','17 A1-3','45 A1-16'], index=df1.index)
df1 = df1.reindex_axis(sorted(df1.columns), axis=1)


df2 = pd.DataFrame([['1 A1-1',5],['2 A1-1',8],['3 A1-1',10],['8 A1-2',4],['17 A1-3',1],['45 A1-16',2]], columns = ['m','n'])

dt = {'A1-1':100, 'A1-2':150, 'A1-3':200, 'A1-4':250, 'A1-5':300, 'A1-16':950}

df1['a']df2['m']包含IDs ,有些是相同的。 df2['n']包含附加值。 dt包含 ID 的基本值类似 A1-1 的群组, A1-2等等

我现在想比较/合并 df1 中的数据, df2dt这样我就可以向 df1 添加新列: 每当IDsdf1['a']df2['m']相同,将字典中具有相同字符串部分的基本值添加到相应的 df2['n'] 中然后结果被转移到 df1['e'] 中的新列中.

我遇到的一个主要问题是 ID 和字典键中的字符串处理:例如 '1 A1-1'df1df2'A1-1'dt - 不知道如何比较它们。

最有帮助的是像 df1['e'] = pd.Series([105,110,154,201,952], index = df1.index) 这样的结果.

感谢您的帮助。

最佳答案

在我看来,这是一个很好解释的问题。

第一split按空白列 a 并使用 str[1] 选择第二个列表,然后使用 map通过 dict 并添加由 set_index 创建的 Seriesmapa :

df1['e'] = df1['a'].str.split().str[1].map(dt) + df1['a'].map(df2.set_index('m')['n'])
print (df1)
          a         b         c         d    e
0    1 A1-1  0.026375  0.260322 -0.395146  105
1    3 A1-1 -0.204301 -1.271633 -2.596879  110
2    8 A1-2  0.289681 -0.873305  0.394073  154
3   17 A1-3  0.935106 -0.015685  0.259596  201
4  45 A1-16 -1.473314  0.801927 -1.750752  952

编辑:

map 函数使用字典的键来替换某些列中的值。与按系列映射类似,只有已安装的键使用 index 值,而 values 使用值。

#sample data
df = pd.DataFrame({'a':['bar','foo', 'baz'], 'b':[7,8,9]})
print (df)
     a  b
0  bar  7
1  foo  8
2  baz  9

#dict and df for mapping
d = {'foo':15, 'bar':20}
df2 = pd.DataFrame({'m':['baz','bar','foo'], 'n':[3,4,5]})
print (df2)
     m  n
0  baz  3
1  bar  4
2  foo  5

#create Series for map
print (df2.set_index('m')['n'])
m
baz    3
bar    4
foo    5
Name: n, dtype: int64

df['c'] = df['a'].map(d)
df['d'] = df['a'].map(df2.set_index('m')['n'])
print (df)
     a  b     c  d
0  bar  7  20.0  4
1  foo  8  15.0  5
2  baz  9   NaN  3

关于python - Pandas,结合来自 2 个数据帧和一本字典的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45438195/

相关文章:

python - 如何避免 pandas 在保存的 csv 中创建索引

json - 有谁知道用于查找单词定义的 Web 服务能够以 JSON 返回结果吗?

c++ - C++14 中 vector 的 unordered_map 和 erase-remove 习语的奇怪行为

python - 无法通过 OpenCV dnn 模块显示 YOLO 结果

python - 如何按给定的索引顺序对 Series 或 DataFrame 进行排序?

python - 如何在不先导出数据框的情况下写入 Excel 工作表?

python - Django - 不保存在 PostGresql 数据库中

python - 如何使用 str.replace 清理列的每一行

c# - 如何通过字典打印列表的内容?

python - pandas groupby sum 需要很长时间,我该如何优化?