如何获得pandas中追加/合并数据帧中的行数?

2024-09-28 21:51:50 发布

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

csv1版本:

import pandas as pd

columns = ['Operations', 'PriceUnit', 'Cost', 'Billingdate']
data = [
    ['abc', 'USD', 45, '2019-12-01T00:00:00Z'],
    ['xyz', 'USD', 30, '2019-12-01T00:00:00Z']
]

df = pd.DataFrame(data, columns=columns)
df

输出:

Operations PriceUnit Cost Billingdate
abc        USD        45  2019-12-01T00:00:00Z
xyz        USD        30  2019-12-01T00:00:00Z

第2版:

columns2 = ['Operations', 'PriceUnit', 'Cost', 'Billingdate']
data2 = [
    ['pqr', 'USD', 19, '2019-12-01T00:00:00Z'],
    ['lmn', 'USD', 27, '2019-12-01T00:00:00Z']
]

df2 = pd.DataFrame(data, columns=columns)
df2

输出:

Operations PriceUnit Cost Billingdate
pqr        USD        19  2019-12-01T00:00:00Z
lmn        USD        27  2019-12-01T00:00:00Z

我在运行脚本时使用argparse传递csv名称。并用以下代码附加这些:

fnames = []
for f in range(1, len(sys.argv)):
    fnames.append(pd.read_csv(sys.argv[f]))

到目前为止还不错,但是当我尝试使用以下方法计算fnames中的行时:

totalRows = len(fnames.index)

它抛出以下错误:

Traceback (most recent call last):
  File "rough.py", line 11, in <module>
    totalRows = len(fnames.index)
TypeError: object of type 'builtin_function_or_method' has no len()

感谢您的帮助。你知道吗


Tags: columnsdataframedfdatalenpdoperationsusd
3条回答
import pandas as pd

# Dataframes
columns = ['Operations', 'PriceUnit', 'Cost', 'Billingdate']
data = [
    ['abc', 'USD', 45, '2019-12-01T00:00:00Z'],
    ['xyz', 'USD', 30, '2019-12-01T00:00:00Z']
]
df = pd.DataFrame(data, columns=columns)

data2 = [
    ['pqr', 'USD', 19, '2019-12-01T00:00:00Z'],
    ['lmn', 'USD', 27, '2019-12-01T00:00:00Z']
]
df2 = pd.DataFrame(data2, columns=columns)

# Merge dataframes
df3 = pd.concat([df, df2])

输出df3

    Operations  PriceUnit   Cost    Billingdate
0   abc USD 45  2019-12-01T00:00:00Z
1   xyz USD 30  2019-12-01T00:00:00Z
0   pqr USD 19  2019-12-01T00:00:00Z
1   lmn USD 27  2019-12-01T00:00:00Z

从形状打印行:

df3.shape[0] # 0 cause the first term is rows and second columns

输出:4

尝试:

len(fnames)

希望有帮助。你知道吗

刚刚看到@abhlib的评论,如果他们愿意,会删除这个吗?你知道吗

fnames是pandas数据帧的列表,如果您想知道有多少个数据帧,只需调用len(fnames) 另一方面,如果您想知道每个数据帧的长度,可以通过[len(df) for df in fnames]得到它们的长度列表。你知道吗

要创建单个数据帧,可以使用pd.concat,whcih沿特定轴连接pandas对象(默认为索引):

df = pd.concat(fnames)

在这一点上,你会发现len(df)将与sum([len(df) for df in fnames])重合

相关问题 更多 >