python - 根据行值对数据框进行子集化,其中行值和列名存储在 VARIABLE 中

标签 python pandas variables dataframe

import pandas as pd
df = pd.DataFrame(data=np.array([["fruit", 12341], ["vegetable", 45642]]))
df.columns = ['this','result']

这就是数据框的样子

     this        result
0    fruit       12341
1    vegetable   45642

“this”和“result”是列名称。 假设其中一个列名存储为名为“var”的字符串变量

“this”列中的行值“fruit”之一作为键存储在名为“dict”的字典中。

var = 'this'
dict = {'fruit': 'apple', 'vegetable': 'orange'}

我正在尝试执行下面代码中显示的一些子集

for k, v in dict.items():
    print(k)
    print(type(k)) #<class 'str'>
    df = df[df.var == k]

df

我知道已经知道了

    df = df[df.this == 'fruit']
    df = df[df.this == 'vegetable']

但是行值和列名称将仅存储为字符串变量!无论如何,您可以对行值和列名称为变量

的数据框进行子集化

除非你们知道,否则我不确定这是否可能。我不介意是否使用 loc 或 iloc 发布解决方案,但我绝对需要将行值和列名称存储在变量中。

我尝试过使用eval之类的方法来打印变量中的值,但无济于事。如果我提出了无法实现的要求,我提前表示歉意。

预期输出将是一个空数据帧,因为df = df[df.var == k]相当于df = df[df.this = = 'fruit']df = df[df.this == 'vegetable'] 当代码迭代字典时,其键是列名 ' 的唯一现有行值这个'

最佳答案

使用isin:

df = df[df[var].isin(dct.keys())]

这消除了循环(好吧,它不会导致空数据帧,但为什么你想要一个空数据帧?)。

请注意,引用具有变量名称的列时不能使用表示法。您需要使用 [...] 语法。有关在哪里可以使用点符号以及在哪里不能使用点符号的更多信息,请参阅 here .

You cannot use the dot notation to access columns if the column name

  • begins with a digit
  • contains whitespace characters
  • contains operator symbols and punctuation
  • conflicts with an existing method name or attribute

The dot notation is similar to accessing object's attributes, and you must follow python's variable naming rules if you want to access them that way. For anything else, you'll have to use [...].

For a more detailed view, view the note at the bottom of the documentation.

此外,不要使用 dict 来命名变量,这会掩盖具有相同名称的内置 dict 类。现在您已经使用了它,请使用 del dict 恢复 dict 功能。

关于python - 根据行值对数据框进行子集化,其中行值和列名存储在 VARIABLE 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46871767/

相关文章:

ios - 是否可以在UITextView中使用变量?

javascript函数来递增数组

javascript - for循环不修改全局变量?

python - 让 Python 忽略 .pyc 文件

python - 如何在python中使用urllib2获取身份验证 token ?

python - 使用日期透视 pandas 数据框并显示每个日期的计数

python - 在每个 pandas 数据框行中查找前 n 个最高值列的名称

python - 有没有办法在使用 Flask 和 Flask-WTForms 循环表单时隐藏 csrf 标签?

python - 迭代 pandas 中的数据框行

python - 将 Alphavantage JSON 文件导入 pandas