簡體   English   中英

python中Series中的元素如何轉換為Dataframe?

[英]How to convert elements in Series to Dataframe in python?

我是 python 的新用戶。

我得到了這樣的 Dataframe:

df = pd.DataFrame({'column_a' : [1, 2, 3], 
                   'conversions' : [[{'action_type': 'type1',
                                      'value': '1',
                                      'value_plus_10': '11'},
                                     {'action_type': 'type2',
                                      'value': '2',
                                      'value_plus_10': '12'}],
                                    np.nan, 
                                    [{'action_type': 'type3',
                                      'value': '3',
                                      'value_plus_10': '13'},
                                     {'action_type': 'type4',
                                      'value': '4',
                                      'value_plus_10': '14'}]]} )

其中列轉換中的值是列表或 NaN。

轉化值如下所示:

print(df['conversions'][0])
>>> [{'action_type': 'type1', 'value': '1', 'value_plus_10': '11'}, {'action_type': 'type2', 'value': '2', 'value_plus_10': '12'}]

但它有點難以操作,所以我希望轉換中的元素是 dataFrame 或 NaN,如下所示:

print(df['conversions'][0])
>>>
  action_type value value_plus_10
0       type1     1            11
1       type2     2            12

print(df['conversions'][1])
>>> nan

print(df['conversions'][2])
>>>
  action_type value value_plus_10
0       type3     3            13
1       type4     4            14

這是我嘗試過的:

df['conversions'] = df['conversions'].apply(lambda x : pd.DataFrame(x) if type(x)=='list' else x)

哪個有效,但沒有真正改變。

我只能找到將系列轉換為 dataframe 的方法,但我想做的是將系列中的元素轉換為數據幀。 有可能嗎? 非常感謝!

編輯:對於不清楚的預期 output 感到抱歉,希望現在清楚了。

您可以將 DataFrame 構造函數應用於conversions列:

df['conversions'] = df['conversions'].apply(lambda x: pd.DataFrame(x) if isinstance(x, list) else x)
print(df['conversions'][0])

Output:

  action_type value value_plus_10
0       type1     1            11
1       type2     2            12

編輯:看來我誤讀了你的問題(待定有點不清楚),因為你聲稱這沒有得到預期的結果。 你想在一個 df 中獲取所有元素嗎? 在這種情況下,您可以使用 concat:

df_out = pd.concat([
    pd.DataFrame(x) for x in df['conversions'] if isinstance(x, list)
])
print(df_out)

Output:

  action_type value value_plus_10
0       type1     1            11
1       type2     2            12
0       type3     3            13
1       type4     4            14

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM