[英]Pandas: How to assign one column value to a variable, based on another column?
I have a DataFrame, for which I want to store values from the keyvalue
column into a variable, based on the value of keyname
.我有一个 DataFrame,我想根据
keyname
的值将keyvalue
列中的值存储到一个变量中。
Example DataFrame:示例 DataFrame:
keyname keyvalue
A 100,200
B 300
C 400
Expected output:预期 output:
v_A = [100, 200]
v_B = 300
v_C = 400
While this is a more verbose approach, it's posted to demonstrate the basic concept for assigning keyvalue
values to a list
variable, based on the value of keyname
.虽然这是一种更详细的方法,但发布它是为了演示基于
keyname
的值将keyvalue
值分配给list
变量的基本概念。
v_A = df.loc[df['keyname'] == 'A', 'keyvalue'].to_list()
v_B = df.loc[df['keyname'] == 'B', 'keyvalue'].to_list()
v_C = df.loc[df['keyname'] == 'C', 'keyvalue'].to_list()
Output: Output:
['100,200']
['300']
['400']
Close, what you need is dictionary with keys and values, because concept of strings variables in python is not recommended :关闭,您需要的是带有键和值的字典,因为不建议在 python 中使用字符串变量的概念:
d = df.set_index('keyname')['keyvalue'].to_dict()
I can suggest two options..我可以建议两个选项..
Convert to a dictionary.. that will give you them as key value pairs, if that is what you want.转换为字典..如果这是您想要的,它将为您提供键值对。
df.set_index('keyname').to_dict()
output: output:
{'keyvalue': {'A': '100,200', 'B': '300', 'C': '400'}}
Take a transpose and you will get them in columns of dataframe and then you can convert as list进行转置,您将在 dataframe 的列中获得它们,然后您可以转换为列表
dft=df.set_index('keyname').T v_A=list(map(int, dft['A'][0].split(","))) v_B=list(map(int, dft['B'][0].split(","))) v_C=list(map(int, dft['C'][0].split(","))) print(v_A) print(v_B) print(v_C)
output: output:
[100, 200]
[300]
[400]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.