替换DF中的单元格是DF中所需行的索引的DF中的单元格

时间:2019-04-01 07:11:58

标签: python pandas

在df1中,每个单元格值都是我要从df2中获取的行的索引。

我想获取df2 trial_ms列中该行的信息,然后根据所获取的df2列重命名df1中的列。

可复制的DF:

# df1

nan = np.NaN
df1 = {'n1': {0: 1, 1: 2, 2: 8, 3: 2, 4: 8, 5: 8},
 'n2': {0: nan, 1: 3.0, 2: 9.0, 3: nan, 4: 9.0, 5: nan},
 'n3': {0: nan, 1: nan, 2: 10.0, 3: nan, 4: nan, 5: nan}}

df1 = pd.DataFrame().from_dict(df1)

# df2

df2 = {
 'trial_ms': {1: -18963961, 2: 31992270, 3: -13028311},
 'user_entries_error_no': {1: 2, 2: 6, 3: 2},
 'user_entries_plybs': {1: 3, 2: 3, 3: 2},
 'user_id': {1: 'seb', 2: 'seb', 3: 'seb'}}

df2 = pd.DataFrame().from_dict(df2)

预期输出:

**n1_trial_ms      n2_trial_ms          n3_trial_ms**

31992270            NaN                 NaN
-13028311           -18934961           NaN

etc.

尝试:

for index, row in ch.iterrows():
        print(row)
        b = df1.iloc[row]['trial_ms']

给我错误:

  

IndexError:位置索引器超出范围

1 个答案:

答案 0 :(得分:1)

我认为您需要trial_ms列中的字典-键是df1的索引,并用get替换值,如果不匹配的值就是错误值NaN:< / p>

d = df2['trial_ms'].to_dict()
df3 = df1.applymap(lambda x: d.get(x, np.nan)).add_suffix('_trial_ms')
print (df3)
   n1_trial_ms  n2_trial_ms  n3_trial_ms
0  -18963961.0          NaN          NaN
1   31992270.0  -13028311.0          NaN
2          NaN          NaN          NaN
3   31992270.0          NaN          NaN
4          NaN          NaN          NaN
5          NaN          NaN          NaN