【发布时间】:2021-03-29 06:45:16
【问题描述】:
问题
我试图在数据框中获取选定的列,但是我试图获取选定列的列必须是唯一的
情景
因此,Dataframe 包含字符串中的所有值,请不要尝试关联任何查看数据的内容。 DF 看起来像这样:
| A | B | C | D | E |
|---|---|---|---|---|
| 12 | Hello | 1 | txt | num |
| 123 | Bello | 2 | txt | doub |
| 7 | nice | 1 | txt | num |
| 54 | duke | 1 | txt | num |
| 9901 | - | 3 | char | doub |
| 63.38 | - | 4 | char | deci |
| 8331 | - | 3 | char | doub |
| 91 | , | 5 | char | num |
我想在C 列上运行.unique() 并获取D 和E 列以及C 的不同/唯一值。
审判
现在,我已经实现了我想要的输出,但我确信这也可以用很少的几行来完成。作为记录,这是我的代码。 main_df 包含上表。
dependent_variables = ["D", "E"]
Dictionary = pd.DataFrame()
new_book = {}
dependent_variables_index = []
for no, col in enumerate(main_df.columns):
print(no, col)
if col in dependent_variables:
dependent_variables_index.append(no)
for cid in total_categories:
try:
new_book[cid] = main_df[main_df["C"] == int(cid)].iloc[0, dependent_variables_index].to_dict()
except KeyError:
new_book[cid] = main_df[main_df["C"] == str(cid)].iloc[0, dependent_variables_index].to_dict()
for k, v in new_book.items():
Dictionary = Dictionary.append(v, ignore_index=True)
Dictionary.index = list(new_book.keys())
Category_Dictionary = Dictionary.reset_index().rename(columns={"index": "C"})
预期输出
| C | D | E |
|---|---|---|
| 1 | txt | num |
| 2 | txt | doub |
| 3 | char | doub |
| 4 | char | deci |
| 5 | char | num |
同样,我可以生成这个输出,但是我正在寻找更优化的方法来做同样的事情。
【问题讨论】:
标签: python pandas dataframe duplicates unique