多键字典中单个键的 Python 访问值

问题描述

我有一个 DataFrame 并试图更改 dtype。 我可以这样做:

#Example
ds = ds.astype({'Breite':float,'Hoehe':float,'Tiefe':float,'vol':float,'Anzahl':np.int64},axis = 1)

我想知道是否可以稍微缩短字典以使其更具可读性,如下所示:

shorter_dict = {('Breite','Hoehe','Tiefe','vol'):float,'Anzahl':np.int64}

ds = ds.astype(shorter_dict,axis=1)

但它想为元组中的每个元素取值。 通过我的搜索,我找到了一个模块:

从 multi_key_dict 导入 multi_key_dict

k[1000,'kilo','k'] = 'kilo (x1000)'

print k[1000] # 将打印 'kilo (x1000)' 打印 k['k'] # 也会打印 'kilo (x1000)'

同样的方式可以更新、删除对象: 如果使用一键更新对象,则新值将 可以使用任何其他密钥访问,例如例如上面: k['千'] = '千' 打印 k[1000] # 现在将在值更新时打印 'kilo'

我现在的问题是:有没有直接在 python 中做同样事情的东西?


编辑: 从这里获得一些帮助 stackoverflow.com/a/41075523/14065969 和这里 https://stackoverflow.com/a/41075515/14065969

我这样做了,并且奏效了:

#Example
import pandas as pd
import numpy as np

shortdict = {('Breite',('Anzahl',):np.int64}

df = pd.DataFrame({'Breite':10,'Hoehe':20,'Tiefe':30,'vol':100,'Anzahl':400},index = [0])

print (df)
print(df.info(),'\n'*2)

for key,value in shortdict.items():
    for inner_key in key:
        df = df.astype({inner_key : value})

print (df)
print(df.info())

输出

   Breite  Hoehe  Tiefe  vol  Anzahl
0      10     20     30  100     400
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1 entries,0 to 0
Data columns (total 5 columns):
 #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   Breite  1 non-null      int64
 1   Hoehe   1 non-null      int64
 2   Tiefe   1 non-null      int64
 3   vol     1 non-null      int64
 4   Anzahl  1 non-null      int64
dtypes: int64(5)
memory usage: 48.0 bytes
None 


   Breite  Hoehe  Tiefe    vol  Anzahl
0    10.0   20.0   30.0  100.0     400
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1 entries,0 to 0
Data columns (total 5 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   Breite  1 non-null      float64
 1   Hoehe   1 non-null      float64
 2   Tiefe   1 non-null      float64
 3   vol     1 non-null      float64
 4   Anzahl  1 non-null      int64  
dtypes: float64(4),int64(1)
memory usage: 48.0 bytes
None
[Finished in 0.7s]```

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)