簡體   English   中英

pandas數據框中的列具有作為值的列表。 如何創建此列的版本,但列表中只有第一個值?

[英]Column in pandas dataframe has lists as values. How do I create a version of this column but with only the first value in the list?

在此處輸入圖片說明

我當前的解決方案如下:

prices_real = []
    for item in sparkline['prices']: 
        prices_real.append(item[0])   
    sparkline['prices_real'] = prices_real

但是我想知道是否有更簡單的方法或我不知道的方法?

您可以使用pandas.Series.apply

sparkline = pd.DataFrame({"prices": [[1], [4]]})
sparkline
#   prices
# 0    [1]
# 1    [4]

sparkline["prices"] = sparkline["prices"].apply(lambda x: x[0])
sparkline
#    prices
# 0       1
# 1       4

您的問題有兩個方面:

  1. 提取系列中每個列表的第一個(也是唯一一個)元素。
  2. 將您的系列轉換為數字。

因此,您可以使用str訪問器,然后使用pd.to_numeric

df = pd.DataFrame({'x': [['0.12312'], ['-5.32454'], ['0.563412'], ['-3.918324']]})

df['x'] = pd.to_numeric(df['x'].str[0])

print(df, df.dtypes, sep='\n'*2)

          x
0  0.123120
1 -5.324540
2  0.563412
3 -3.918324

x    float64
dtype: object

暫無
暫無

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

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