【问题标题】:Convert Pandas Object to Array将 Pandas 对象转换为数组
【发布时间】:2020-07-30 21:21:36
【问题描述】:

我在数据框中有一列属于对象类型。我想将其转换为数组。 例如:

'["399866273","12444645","162497334"]'

我知道将其转换为字符串并根据, 拆分它。但我想知道是否有更好的方法来做到这一点。

【问题讨论】:

  • 如果你的意思是numpy.ndarray,那么你只需要my_df['column'].values,如果你想要一个列表,那么你只需要my_df['column'].to_list()
  • 我不能这样做,它会说'str'对象没有属性'values'@juanpa.arrivillaga
  • 那么你没有数据框你有str。你是如何产生这个字符串的?您需要提供minimal reproducible example
  • 为你得到的对象尝试 dir(SomeObject)。它可能有助于确定您正在处理的内容。
  • @Mike67 或只是type(my_object)

标签: python arrays dataframe


【解决方案1】:
import json
import numpy as np

def toarray(s):
    x = json.loads(s)
    arr = np.array(x)
    return arr

# Test
s = '["399866273","12444645","162497334"]'
asset type(toarray(s)) == np.ndarray
assert all(toarray(s) == np.array(["399866273", "12444645", "162497334"]))

# Apply to df
colname = ...  # your col name
df['as_array'] = df[colname].apply(toarray)

【讨论】:

    【解决方案2】:

    你可以试试这样的:

    df = pd.DataFrame(['["399866273","12444645","162497334"]'], columns = ['Column_ObjectType'])
    
    df.dtypes
    #output
    Column_ObjectType    object
    dtype: object
    
    df[['Value1','Value2','Value3']] = df.Column_ObjectType.str.split(",", expand=True)
    df.head()
    #output
                          Column_ObjectType        Value1      Value2        Value3
    0  ["399866273","12444645","162497334"]  ["399866273"  "12444645"  "162497334"]
    
    df['Value1'] = df.Value1.apply(lambda x: x[2:-1])
    df['Value2'] = df.Value1.apply(lambda x: x[1:-1])
    df['Value3'] = df.Value1.apply(lambda x: x[1:-1])
    df.head()
    #output
                      Column_ObjectType     Value1    Value2    Value3
    0  ["399866273","12444645","162497334"]  399866273  39986627  39986627
    

    【讨论】:

      【解决方案3】:

      如果您的意思是列表,您可以使用eval()

      【讨论】:

        猜你喜欢
        • 2018-10-27
        • 2021-08-11
        • 2017-09-26
        • 1970-01-01
        • 2021-05-03
        • 2018-12-04
        • 2021-06-16
        • 1970-01-01
        相关资源
        最近更新 更多