0

我有一个类似的数据框

import pandas as pd
df = pd.DataFrame({'a': ['A', 'A'],
                   'b': ['B', 'D'],
                   'c': ['C', 'C'],
                   'd': ['D', 'D']},
                   index=[0, 1])

如果该行具有相同的值,我想保留正确的单元格

愿望输出

  0  1
0    A
1 B  D
2    C
3    D

我已经尝试过df = pd.DataFrame(list(map(pd.unique, df.values))) ,但它会将值推到最近的左侧,这不是我想要的输出。

谢谢您的帮助

4

3 回答 3

2

这应该适合你:

import pandas as pd
df = pd.DataFrame({'a': ['A', 'A'],
                   'b': ['B', 'D'],
                   'c': ['C', 'C'],
                   'd': ['D', 'D']},
                   index=[0, 1])

df=df.T #Transposing the dataframe

def SameValue(row):
    if row[0] == row[1]:
        return ''        #If the rows match return an empty string
    else:
        return row[0]    #If the rows do not match return the original value


df[0] = df.apply(SameValue, axis=1)   #Apply the SameValue function on the dataframe

print(df)

请让我知道它是否有效

于 2021-04-28T03:05:58.600 回答
0

使用 pythonic 方式而不是 pandas 数据框:


df = pd.DataFrame({'a': ['A', 'A'],
                   'b': ['B', 'D'],
                   'c': ['C', 'C'],
                   'd': ['D', 'D']},
                   index=[0, 1])
 

data_in_dict = df.to_dict()
for key in data_in_dict:
   if data_in_dict[key][0] == data_in_dict[key][1]
      data_in_dict[key][0] = ''

final_data_frame = pd.DataFrame(data_in_dict, index=[0,1])
print(final_data_frame.T)
于 2021-04-28T03:26:49.753 回答
0

最简单的方法是:

df = df.T # Transpose of the datafame
df.loc[df[0]==df[1],0] = '' # Find where column 0 and 1 are equal and change the value of column 0 to empty string
于 2021-04-28T03:10:47.957 回答