Pandas基于相同的ID填充空值

2024-04-26 02:47:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数据帧。你知道吗

我的第一个数据,但第二行B列缺少一个值。你知道吗

enter image description here

我的第二个数据在第二行的B列中有这个值

enter image description here

我希望第二个数据填充第一个数据的空值。你知道吗

我尝试了以下代码:

import pandas as pd

test1 ='test1.xlsx'
test2 ='test2.xlsx'

df1 = pd.excel(test1)
df2 = pd.excel(test2)

df3 = pd.merage(df1, df2, on='clolumns', how='left')

df3.to_excel('df3.xlsx')

结果将是columns2\ux和columns2\uy,我想合并成一列。你知道吗


Tags: 数据代码importpandasasxlsxexcelpd
2条回答

你可以试试combine_first函数

>>> df1 = pd.DataFrame({ 'A': [123, 1234, 12345], 'B' : ['str1', None, 'str3']})
>>> df2 = pd.DataFrame({ 'A': [123, 1234, 12345], 'B' : [None, 'str2', None]})
>>> result = df1.combine_first(df2)
>>> result
       A     B
0    123  str1
1   1234  str2
2  12345  str3

一个选项是使用np.where

df2['columns2_x'] = np.where(df2['columns2_x'] == '', df2['columns2_y'], df2['columns2_x'])

另一种选择是将updatedf1与文件化df2

一起使用
df1.update(df2[df2['columns1'].isin(df1[df1['columns2'] == '']['columns1'])])

相关问题 更多 >