python - Pandas ,将系列连接到 DF 作为行

标签 python pandas concat series

我试图将一个系列添加到一个空的 DataFrame 中,但找不到答案 在文档或其他问题中。因为您可以按行附加两个 DataFrame 或者按列看来系列中必须缺少一个“轴标记”。能 谁能解释为什么这不起作用?

import Pandas as pd
df1 = pd.DataFrame()
s1 = pd.Series(['a',5,6])
df1 = pd.concat([df1,s1],axis = 1)
#go run some process return s2, s3, sn ...
s2 = pd.Series(['b',8,9])
df1 = pd.concat([df1,s2],axis = 1)
s3 = pd.Series(['c',10,11])
df1 = pd.concat([df1,s3],axis = 1)

If my example above is some how misleading perhaps using the example from the docs will help.

Quoting: Appending rows to a DataFrame.
While not especially efficient (since a new object must be created), you can append a single row to a DataFrame by passing a Series or dict to append, which returns a new DataFrame as above. End Quote.

The example from the docs appends "S", which is a row from a DataFrame, "S1" is a Series and attempting to append "S1" produces an error. My question is WHY will appending "S1 not work? The assumption behind the question is that a DataFrame must code or contain axes information for two axes, where a Series must contain only information for one axes.

df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])
s = df.xs(3); #third row of DataFrame
s1 = pd.Series([np.random.randn(4)]); #new Series of equal len
df= df.append(s, ignore_index=True)

结果

   0  1

0  a  b

1  5  8

2  6  9

想要的

   0  1 2

0  a  5 6

1  b  8 9

最佳答案

你很接近,只是转置了 concat

的结果
In [14]: s1
Out[14]: 
0    a
1    5
2    6
dtype: object

In [15]: s2
Out[15]: 
0    b
1    8
2    9
dtype: object

In [16]: pd.concat([s1, s2], axis=1).T
Out[16]: 
   0  1  2
0  a  5  6
1  b  8  9

[2 rows x 3 columns]

您也不需要创建空的 DataFrame

关于python - Pandas ,将系列连接到 DF 作为行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21004993/

相关文章:

python - module._init_() 最多接受 2 个参数(给定 3 个)(scrapy 教程 w/xpath)

python - DataFrame 操作函数/方法

python - PyTorch BERT 类型错误 : forward() got an unexpected keyword argument 'labels'

javascript - 在 PHP 字符串中插入 JS 变量

python - 将多个csv文件导入pandas并合并成一个DataFrame

python - 如何将选定的列附加到具有不同列的 df 中的 pandas 数据框

python - 合并具有两个公共(public)值的行 | Python

python-3.x - 如何一次性将 df 列值映射到十六进制颜色?

Python Pandas : dataframe. loc 返回 "KeyError: label not in [index]",但 dataframe.index 显示它是

react-native - 附加两个音频文件 React Native