从系列字典中获得第一价值

时间:2018-07-24 08:02:07

标签: pandas

我有一个熊猫系列orders['customer'],看起来像这样:

0      {'id': 454543543533, 'email': 'aaaaaa@gmail.com...
1      {'id': 437890767654, 'email': 'bbbbbbbb@mail.com...
2      {'id': 534764345453, 'email': 'ccccccccc@mail.com..
3      {'id': 345436564353, 'email': None, 'accepts_m....
4      {'id': 671341215803, 'email': None, 'accepts_m...
5      {'id': 671317065787, 'email': None, 'accepts_m...

我想遍历该系列的行并获取每个字典的第一个元素(id)。此外,我想只用id代替系列中的值。

我尝试了许多不同的解决方案,最后一个解决了这个问题,但是我无法使这件事起作用:

for i in range(len(orders_df['customer'].values.tolist())):
    orders_df['customer'] = orders_df['customer'].values.tolist()[i]

1 个答案:

答案 0 :(得分:1)

如果带有键 package sample; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.layout.*; import javafx.scene.control.*; import javafx.scene.layout.FlowPane; import javafx.stage.Stage; public class Main extends Application { public static void main(String[] args) { launch(args); } public void start(Stage myStage){ myStage.setTitle("Demonstrate a Simple Scene Graph"); FlowPane rootNode = new FlowPane(); Scene myScene = new Scene (rootNode,500,500); myStage.setScene(myScene); Label myLabel = new Label ("A simple JavaFX label."); rootNode.getChildren().add(myLabel); myStage.show(); } } 的字典否则将lambda函数与get用作匹配值,否则返回默认值,此处为id

0

或者:

orders_df = pd.DataFrame({'customer':[{'id': 454543543533, 'email': 'fdgr@gmail.com'}, 
                                      {'id': 437890767654, 'email': 'ereffewf@mail.com'},
                                      {'email': 'ereffewf@mail.com'}]})
print (orders_df)
                                            customer
0    {'id': 454543543533, 'email': 'fdgr@gmail.com'}
1  {'id': 437890767654, 'email': 'ereffewf@mail.c...
2                     {'email': 'ereffewf@mail.com'}

orders_df['customer'] = orders_df['customer'].apply(lambda x: x.get('id', 0))

orders_df['customer'] = [x.get('id', 0) for x in orders_df['customer']]