我有带有数据的Excel电子表格,每年一次。可惜的是,一年中列的变化很小。我想要的是拥有一个包含所有数据的数据框,并用预定义的数据填充缺少的列。我写了一个小的示例程序来测试它。
import numpy as np
import pandas as pd
# Initialize three dataframes
df1 = pd.DataFrame([[1,2], [11,22],[111,222]], columns=['een', 'twee'])
df2 = pd.DataFrame([[3,4], [33,44],[333,444]], columns=['een', 'drie'])
df3 = pd.DataFrame([[5,6], [55,66],[555,666]], columns=['twee', 'vier'])
# Store these in a dictionary and print for verification
d = {'df1': df1, 'df2': df2, 'df3': df3}
for key in d:
print(d[key])
print()
# Create a list of all columns, as order is relevant a Set is not used
cols = []
# Count total number of rows
nrows = 0
# Loop thru each dataframe to determine total number of rows and columns
for key in d:
df = d[key]
nrows += len(df)
for col in df.columns:
if col not in cols:
cols += [col]
# Create total dataframe, fill with default (zeros)
data = pd.DataFrame(np.zeros((nrows, len(cols))), columns=cols)
# Assign dataframe to each slice
c = 0
for key in d:
data.loc[c:c+len(d[key])-1, d[key].columns] = d[key]
c += len(d[key])
print(data)
可以正确初始化数据帧,但是分配给数据数据帧的切片有些奇怪。我想要(并且期望)的是:
een twee drie vier
0 1.0 2.0 0.0 0.0
1 11.0 22.0 0.0 0.0
2 111.0 222.0 0.0 0.0
3 3.0 0.0 4.0 0.0
4 33.0 0.0 44.0 0.0
5 333.0 0.0 444.0 0.0
6 0.0 5.0 0.0 6.0
7 0.0 55.0 0.0 66.0
8 0.0 555.0 0.0 666.0
但这就是我得到的:
een twee drie vier
0 1.0 2.0 0.0 0.0
1 11.0 22.0 0.0 0.0
2 111.0 222.0 0.0 0.0
3 NaN 0.0 NaN 0.0
4 NaN 0.0 NaN 0.0
5 NaN 0.0 NaN 0.0
6 0.0 NaN 0.0 NaN
7 0.0 NaN 0.0 NaN
8 0.0 NaN 0.0 NaN
第一个数据帧的位置和数据已正确分配。但是,第二个数据帧分配给了正确的位置,但没有分配给它的内容:NaN被分配了。第三个数据框也会发生这种情况:正确的位置但缺少数据。我曾尝试assign d[key].loc[0:2, d[key].columns
和一些更奇妙的解决方案来解决数据切片,但都返回NaN。如何获得已分配给数据的数据框内容?
答案 0 :(得分:1)
根据评论,您可以使用:
pd.concat([df1, df2, df3])
OR
pd.concat([df1, df2, df3]).fillna(0)