如何将键的值分配为pandas的行值



给定这个datframe:

{'index': {0: 0, 1: 1},
'speed': {0: {'value': ['3'], 'comment': ''},
1: {'value': ['2'], 'comment': ''}},
'rotor': {0: {'value': ['2'], 'comment': ''},
1: {'value': ['3'], 'comment': ''}}}

我怎么能只得到value键作为这个输出:

pd.DataFrame({'index': [0,1],'speed': [3,2],'rotor': [2,3]})

我尝试了df.apply(lambda x: x.get('value')df.apply(lambda x: x.get('value'), axis=1,没有成功

您必须选择列并使用str.get(或str['value']):

cols = ['speed', 'rotor']
df[cols] = df[cols].apply(lambda x: x.str.get('value'))

输出:

index speed rotor
0      0   [3]   [2]
1      1   [2]   [3]

如果你只想要整数值:

cols = ['speed', 'rotor']
df[cols] = df[cols].apply(lambda x: x.str.get('value').str[0]).astype(int)

输出:

index  speed  rotor
0      0      3      2
1      1      2      3

替代使用applymap:

cols = ['speed', 'rotor']
df[cols] = df[cols].applymap(lambda x: int(x['value'][0]))

最新更新