列的共同价值观我有风格的数据帧:行d查找熊猫数据帧
animal animal
A Dog Dog
B Cat Cat
C Pig Pig
D Cat Dog
不同的条目告诉我有一个错误。我需要删除动物不一样的所有行。这些列具有相同的名称。
我相信这应该很简单! 非常感谢。
列的共同价值观我有风格的数据帧:行d查找熊猫数据帧
animal animal
A Dog Dog
B Cat Cat
C Pig Pig
D Cat Dog
不同的条目告诉我有一个错误。我需要删除动物不一样的所有行。这些列具有相同的名称。
我相信这应该很简单! 非常感谢。
准备性代码会生成与您的结构相同的数据帧。有趣的是,我无法命名animal
列,并加入suffix = ("","")
- 这会引发错误ValueError: columns overlap but no suffix specified: Index([u'animal'], dtype='object')
。 @ chrisaycock的评论重新命名的列工作得很好。
import pandas as pd
# prepare the dataframe
a1 = ['Dog','Cat','Pig','Cat']
a2 = ['Dog','Cat','Pig','Dog']
df1 = pd.DataFrame({"ani": a1})
df2 = pd.DataFrame({"ani": a2})
# trickery required to get two columns with the same name
df = pd.merge(df1, df2, left_index=True,right_index = True, suffixes=("mal", "mal"))
# fix the column names
df.columns = ['animal1', 'animal2']
# keep only matching rows
df = df[df.animal1 == df.animal2]
根据索引遍历数据帧并检查返回值。
>>> for i in df.index:
... if len(set(df.ix[i])) != 1:
... df.drop(i)
迭代DataFrame是非常不理想的。 – chrisaycock
出于好奇,你是如何得到一个DataFrame与同名的列?你能强迫他们改变吗? 'df.columns = ['animal1','animal2']'。 – chrisaycock
谢谢 - 我继承了数据框。 –
检查了源代码。如果任何人感兴趣数据是由pd.concat([df1,df2],axis = 1)产生的 –