gpt4 book ai didi

python - 查找值的位置,在数据框中只出现一次

转载 作者:太空宇宙 更新时间:2023-11-03 10:56:09 26 4
gpt4 key购买 nike

我很难找到最好的“python 方式”来取回 pandas DataFrame 中的位置(行|列)值。

我有一个数字列表...list = [1,2,3,4,5,8]

和一个 pandas 数据框。

df = pd.DataFrame({'A':[1,3,8,8], 'B':[3,3,2,8],'x':[0.4,0.3,0.5,0.8]})

df
Out[2]:
A B x
0 1 3 0.4
1 3 3 0.3
2 8 2 0.5
3 8 8 0.8
  1. 我会将列表中的数字与 DataFrame 中的数字(['A'] 和 ['B'])进行比较。最后我想知道,列表中的哪个数字只在 DataFrame 中出现一次。

我会用列表中的每个数字遍历 DataFrame,但我认为这不是最好的 Python 方式。

  1. 我需要数据帧中一次出现值的位置(行|列),因为如果单个数字在 df['B'] 中,那么我需要额外的 df['A'] 值.如果单个数字在 df['A'] 中,我需要在 df['B'] 中添加值,

我不知道如何解决这个问题...如果您有一些搜索关键字,我会很高兴,这样我就可以解决这个问题。

稍后我将复制该行,其中包括新的 DataFrame 中的单个数字和数字后面的值。

目标是得到下面的输出...

dfnew

SingleNumber AorB x
0 1 3 0.4
1 2 8 0.5

我很高兴每一个信息都可以解决这个问题。如果您需要更多背景信息,请告诉我。

PS:我是初学者:)

最佳答案

鉴于您的出发点(注意我已将 list 重命名为 data 否则它会隐藏内置函数):

data = [1,2,3,4,5,8]
df = pd.DataFrame({'A':[1,3,8,8], 'B':[3,3,2,8],'x':[0.4,0.3,0.5,0.8]})

首先,展平你的框架,这样你就只有一个列可以使用:

flattened = pd.melt(df, value_vars=['A', 'B'])

这给了你:

  variable  value
0 A 1
1 A 3
2 A 8
3 A 8
4 B 3
5 B 3
6 B 2
7 B 8

然后过滤 data 中的值(在本例中它返回相同的数据帧,因此我不会复制/粘贴与上面相同的结果):

in_data = flattened[flattened.value.isin(data)]

然后删除所有重复值:

only_once = in_data.drop_duplicates(subset='value', keep=False)

这给了你:

  variable  value
0 A 1
6 B 2

然后你可以使用它的索引来回到你原来的 DF:

new_df = df.iloc[only_once.index // len(df.columns)]

这给了你:

   A  B    x
0 1 3 0.4
2 8 2 0.5

然后分配列...

new_df['single_number'] = only_once.value.values

最终结果是:

   A  B    x  single_number
0 1 3 0.4 1
2 8 2 0.5 2

这会保留您的原始索引值,如果您真的想要新的索引值,请查看 .reset_index(drop=True) 以获取 0 和 1。


在以下评论之后取回原始数据的更聪明的方法:

For example...let me change the df to df = pd.DataFrame({'A':[1,3,8,5], 'B':[3,3,2,8],'x':[0.4,0.3,0.5,0.8]}). When I compute the new_df I get a wrong result.

请注意,这不包括根据列表检查值。

使用重置索引展平列,使其成为以后可用的列,并从中删除所有重复值。

df = pd.DataFrame({'A':[1,3,8,5], 'B':[3,3,2,8],'x':[0.4,0.3,0.5,0.8]})
unique = pd.melt(
df.reset_index(),
id_vars='index',
value_vars=['A', 'B'],
value_name='SingleNumber'
).drop_duplicates(subset='SingleNumber', keep=False)

这给了你:

   index variable  value
0 0 A 1
3 3 A 5
6 2 B 2

然后使用其索引和之前保留的索引列将其与原始框架合并。

new_df = df.merge(unique, left_index=True, right_on='index')

你最终得到:

   A  B    x  index variable  SingleNumber
0 1 3 0.4 0 A 1
6 8 2 0.5 2 B 2
3 5 8 0.8 3 A 5

然后根据需要删除或重命名列或重置索引等。

关于python - 查找值的位置,在数据框中只出现一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40548864/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com