如何用Pandas从DataFrame拆分列

2024-04-26 11:26:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在将一个CSV文件从一个API调用读入一个带有pandas的数据帧,以便进行一些数据操作。你知道吗

目前,我得到的答复是:

n [78]: dfname
Out[78]: 
        productID  amountInStock  index  index_col
7             1.0            NaN      1          7
19            4.0            NaN      2         19
20            1.0            NaN      3         20
22            2.0            NaN      4         22

然后我打电话dfname.reset\u索引()要创建更好的索引:

dfname.reset_index()
Out[80]: 
      level_0  productID  amountInStock  index  index_col
0           7        1.0            NaN      1          7
1          19        4.0            NaN      2         19
2          20        1.0            NaN      3         20
3          22        2.0            NaN      4         22

但问题是'productID'系列有两列,我无法解决如何拆分它们!你知道吗

dfname.productID
Out[82]: 
7          1.0
19         4.0
20         1.0
22         2.0

我想要的是dfname.productID返回:

dfname.productID
Out[82]: 
7          
19         
20         
22         

而productID中当前的其他数字应该分配给“stockqty”。你知道吗

如何拆分此字段,使其返回两列而不是一列?我试过了。结构拆分()无济于事。你知道吗

对象的属性为Name:productID、Length:2102、dtype:float64


Tags: 文件csv数据apipandasindex数字col
2条回答

我在解析csv时指定了分隔符:

        df = pd.read_csv(link, encoding='ISO-8859-1', sep=', ', engine='python')

But the problem is that the 'productID' series has two columns and I can't work out how to split them!

这就是误解。不管print告诉您什么,您没有2列。您有一个索引为的列。这正是^{}对象的定义方式。你知道吗

What I want is dfname.productID to return:

如上所述,这是不可能的。每个系列都有一个索引。这是不可商量的。你知道吗

How do I split this field so that it returns two columns instead of one? I've tried .str.split() to no avail.

这不是前进的方向。特别是,注^{}用于在序列中拆分字符串。你这里没有线。相反,使用reset_index并重命名列。或者将索引命名在reset_index之前。在我看来,后一种选择更为清晰:

df.index.name = 'stockqty'
df = df.reset_index()

print(df)

   stockqty  productID  amountInStock  index  index_col
0         7        1.0            NaN      1          7
1        19        4.0            NaN      2         19
2        20        1.0            NaN      3         20
3        22        2.0            NaN      4         22

相关问题 更多 >